1

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.

5 Answers 5

2

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****@'));

Sign up to request clarification or add additional context in comments.

1 Comment

This is good because it replaces the remaining letters with four asterisks as requested, not "however many remaining letters there were" asterisks.
1

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

1 Comment

'*'.repeat(e.length - 2) is probably not ideal from a privacy POV; perhaps a hardcoded value would be better.
0

First get your index of @ With

Var ind =str.indexof("@")

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

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.