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 :
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.
// 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");
// 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*");
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
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"