我需要使用 javascript 隐藏部分字符串,我有电子邮件:
hideparts@email.com
我需要变成:
hi****@email.com
而且我需要在@ 之后显示电子邮件,但我不知道该怎么做。
答案 0 :(得分:2)
RegExp 可能很好。 Regex Editor
。
保留前两个字母并替换要替换的@
之前的其余字母
let str = 'hideparts@email.com';
console.log(str.replace(/(\w{2}).*?@/, '$1****@'));
答案 1 :(得分:1)
这是使用 map() 和 repeat() 的快速方法
let email = "hideparts@email.com";
const obfuscate = str => str.split('@').map((e, i) => i === 0 ? e.slice(0, 2) + '*'.repeat(e.length - 2) : e).join('@');
console.log(obfuscate(email))
答案 2 :(得分:0)
首先获取@的索引 随着
false
然后从索引 2 循环到 ind,每个循环用 * 替换这个字符
答案 3 :(得分:0)
我觉得这可以使用 indexOf()
和 for 循环来实现。
let email = 'hideparts@email.com';
let atPosition = email.indexOf('@'); //get @ position
let startIndex = atPosition > 2 ? 2: 0; //handle case for really small email names
if(atPosition > -1){
for(let i = startIndex ; i < atPosition;i++){
email = email.substring(0, i) + '*' + email.substring(i + 1);
}
}
console.log(email);
使用 .subtstring()
方法替换字符串中的字符。
email[i] = '*'
不起作用,字符串是不可变的。
答案 4 :(得分:0)
您可以使用以下代码来实现您的需求。
const str = 'abcdefgh@email.com';
const [contact, domain] = str.split('@');
const maskedMailId = contact.slice(0, 2) + '*'.repeat(contact.length - 2) + '@' + domain;
console.log(maskedMailId);