0

I wanna mask a name with the provisions that if there are more than 4 letters it will form the following masking :

Jason Mamoa ---> Ja**n Ma**a

I have tried this :

var name ="Jason Mamoa";
var regex =/\b[^\W]{2}([^\W]{2,})[^\W]\b/g;
console.log(nama.replace(regex,"**$1*"));

but the opposite happened, like this :

Jason Mamoa --> **so* **mo*
0

1 Answer 1

2

You need to go the other way around - capture the first two letters, and the last letter, and replace with them separated by **:

var name ="Jason Mamoa";
var regex =/\b(\w{2})\w+(\w)\b/g;
console.log(name.replace(regex, '$1**$2'));

If you want the resulting string to be the same length as the original, use a replacer function:

var name ="Jason Mammmmoa";
var regex =/\b(\w{2})(\w+)(\w)\b/g;
console.log(name.replace(
  regex,
  (_, first, middle, last) => `${first}${'*'.repeat(middle.length)}${last}`
));

Note that [^\W] is equivalent to \w.

To also mask the last 2 characters of 3 and 4 character names, capture up to 2 leading characters, and have the last be optional:

var name ="Eli Mose";
var regex =/\b(\w{1,2})(\w{2,}?)(\w?)\b/g;
console.log(name.replace(
  regex,
  (_, first, middle, last) => `${first}${'*'.repeat(middle.length)}${last}`
));

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

4 Comments

what if in one word there are 3-4 letters it will make masking as follows: Eli Mose ---> E** Mo**
You said in your question that you only wanted masking for 5+ characters?
if there are several conditions
Thanks for the answer to my question

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.