admin管理员组文章数量:1326287
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 badges2 Answers
Reset to default 5You 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, '*');
本文标签: javascriptHow replace characters with asterisks (*) except first two charactersStack Overflow
版权声明:本文标题:javascript - How replace characters with asterisks (*) except first two characters - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742209872a2433511.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论