Reputation: 467
I need to hide parts of a string using javascript, I have the email:
[email protected]
And I need to transform into:
hi****@email.com
And I need to display the email after the @, but I don't know how to do this.
Upvotes: 1
Views: 290
Reputation: 71
You can use the below code to achieve what you need.
const str = '[email protected]';
const [contact, domain] = str.split('@');
const maskedMailId = contact.slice(0, 2) + '*'.repeat(contact.length - 2) + '@' + domain;
console.log(maskedMailId);
Upvotes: 0
Reputation: 20626
I feel this could be achieved using indexOf()
and a for loop.
let email = '[email protected]';
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);
Using the .subtstring()
method to replace a character in a string.
email[i] = '*'
will not work, strings are immmutable.
Upvotes: 0
Reputation: 4011
A RegExp might be good. Regex Editor
.
Leaving the first two letters and replacing the rest before the @
to be replaced
let str = '[email protected]';
console.log(str.replace(/(\w{2}).*?@/, '$1****@'));
Upvotes: 2
Reputation: 23664
Here's a quick way using map() and repeat()
let email = "[email protected]";
const obfuscate = str => str.split('@').map((e, i) => i === 0 ? e.slice(0, 2) + '*'.repeat(e.length - 2) : e).join('@');
console.log(obfuscate(email))
Upvotes: 1
Reputation: 577
First get your index of @ With
Var ind =str.indexof("@")
then loop from index 2 to ind and each loop replace this char with *
Upvotes: 0