How do I make masking in the first name, middle name,and last name in JavaScript?


How do I make masking in the first name, middle name, and last name? Make masking based on the number of letters in each word in the name. under the condition :

  1. if one word contains 2 letters then there is no masking
  2. if there are 3-4 letters then the first two letters will be masked.
  3. If there are more 4 letters, the first 2 letters and the last 1 letter will be masked.

Example :

1.”Jo Dyne Roger” –> “Jo **ne **ge*”

2.”Samantha Summer” –> “**manth* **mme*”

I have tried to calculate the length of one word and after that masking. but I don’t know what if there are more than two word

function nameMasking(name) { 
 var masking = "";
 var replace = "*";
 for(var i = 0; i < name.length-3; i++){ 
    masking = masking + replace; 
    accountNum = masking + name.substring(name.length+2, name.length);
    return name;

Any suggestions?


You can do this using Regular Expressions.

For case 2 (words with 3 or 4 letters):

// match 2 letters, then 1 or 2 more letters
var regex1 = /b[^W]{2}([^W]{1,2})b/g;
// replace first 2 letters with **, leave the rest
name = name.replace(regex1,"**$1");

For case 3 (words with 5+ letters):

// match 2 letters, then 2 or more letters, then 1 more letter
var regex2 = /b[^W]{2}([^W]{2,})[^W]b/g;
// replace first 2 with **, replace last letter with *, leave the middle
name = name.replace(regex2,"**$1*");

All together:

function mask(name) {
    var regex1 = /b[^W]{2}([^W]{1,2})b/g;
    var regex2 = /b[^W]{2}([^W]{2,})[^W]b/g;
    return name.replace(regex1,"**$1").replace(regex2,"**$1*");


mask("Jo Dyne Roger");    // returns "Jo **ne **ge*"
mask("Samantha Summer");  // returns "**manth* **mme*"


  • b matches word boundaries.

  • [^W] matches any non-whitespace characters

  • {2} tells it to find 2 occurrences, {1,2} means 1 or 2, {2,} means 2 or more

  • g at the end is for global (matches all applicable words in the string)

  • $1 in the replacement matches a group captured with parentheses

New function based on comments:

function mask2(name) {
    // match (first 2 letters), (2 or more middle letters), (last letter)
    var regex = /b([^W]{2})([^W]{2,})([^W])b/g;
    // leave 1st and 3rd groups, but replace letters in second group with stars
    return name.replace(regex, function(m,g1,g2,g3) {
        return g1+g2.replace(/[^W]/g,"*")+g3;

You can additional replacements for masking 1-4 letter words just like in the first function.


mask2("Steven Harts");   // returns "St***n Ha**s"
mask2("Jo Dyne Roger");  // returns "Jo Dyne Ro**r"

Source: stackoverflow