最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How replace characters with asterisks (*) except first two characters - Stack Overflow

programmeradmin3浏览0评论

I want to mask the data returned from the API with Asterisk (*). For example, if an address is to be returned from the API, I want only the first 2 letters to be visible.

Example: Lorem Ipsum is simply dummy text of the printing and typesetting industry.

What i want: Lo*** Ip*** is si**** du*** .....

I created a sample API and I don't know how to find a solution. I thought I could convert text to asterisk with replace, but I have no idea how to make the first 2 letters appear.

Demo: Here

If you have any ideas about what I should do and share it, I would appreciate it.

I want to mask the data returned from the API with Asterisk (*). For example, if an address is to be returned from the API, I want only the first 2 letters to be visible.

Example: Lorem Ipsum is simply dummy text of the printing and typesetting industry.

What i want: Lo*** Ip*** is si**** du*** .....

I created a sample API and I don't know how to find a solution. I thought I could convert text to asterisk with replace, but I have no idea how to make the first 2 letters appear.

Demo: Here

If you have any ideas about what I should do and share it, I would appreciate it.

Share Improve this question asked Mar 2, 2021 at 7:14 ogulcanogulcan 1451 gold badge5 silver badges13 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You could do it like this

const s = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.";

function hideWord(w) {
    if (w.length < 3) return w;
    return w.substring(0, 2) + '*'.repeat(w.length-2);
}

console.log(s.split(" ").map(hideWord).join(" "));

Output is

Lo*** Ip*** is si**** du*** te** of th* pr****** an* ty********* in*******

Split the string into words and then map each word top its hidden version and rejoin. To map it simply return any 1 or 2 letter length words as they were and for others take a substring of the first two chars and fill the rest with asterisks.

You could also wrap the whole lot in a function if you wanted to be able to call it from multiple places and avoid redefining it.

function hideWords(s) {
    return s.split(" ").map(hideWord).join(" ");
}

console.log(hideWords(s));

I would use regex with lookbehind assertion

const text = 'Lorem Ipsum is simply dummy text of the printing & typesetting industry';
const result = text.replaceAll(/(?<=\w{2,})\w/g, '*');
发布评论

评论列表(0)

  1. 暂无评论