Javascript replace some parts of string

Viewed 96

I need to hide parts of a string using javascript, I have the email:

hideparts@email.com

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.

5 Answers

A RegExp might be good. Regex Editor.

Leaving the first two letters and replacing the rest before the @ to be replaced

let str = 'hideparts@email.com';

console.log(str.replace(/(\w{2}).*?@/, '$1****@'));

Here's a quick way using map() and 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))

First get your index of @ With

Var ind =str.indexof("@")

then loop from index 2 to ind and each loop replace this char with *

I feel this could be achieved using indexOf() and a for loop.

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);

Using the .subtstring() method to replace a character in a string. email[i] = '*' will not work, strings are immmutable.

You can use the below code to achieve what you need.

const str = 'abcdefgh@email.com';
const [contact, domain] = str.split('@');
const maskedMailId = contact.slice(0, 2) + '*'.repeat(contact.length - 2) + '@' + domain;
console.log(maskedMailId);

Related