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 :
- if one word contains 2 letters then there is no masking
- if there are 3-4 letters then the first two letters will be masked.
- 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?
Advertisement
Answer
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 = /bS{2}(S{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 = /bS{2}(S{2,})Sb/g;
// replace first 2 with **, replace last letter with *, leave the middle
name = name.replace(regex2,"**$1*");
All together:
function mask(name) {
var regex1 = /bS{2}(S{1,2})b/g;
var regex2 = /bS{2}(S{2,})Sb/g;
return name.replace(regex1,"**$1").replace(regex2,"**$1*");
}
Usage:
mask("Jo Dyne Roger"); // returns "Jo **ne **ge*"
mask("Samantha Summer"); // returns "**manth* **mme*"
Explanation:
bmatches word boundaries.Smatches any non-whitespace characters{2}tells it to find 2 occurrences,{1,2}means 1 or 2,{2,}means 2 or moregat the end is for global (matches all applicable words in the string)$1in 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(S{2})(S{2,})(S)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(/./g,"*")+g3;
});
}
You can do additional replacements for masking 1-4 letter words just like in the first function.
Usage:
mask2("Steven Harts"); // returns "St***n Ha**s"
mask2("Jo Dyne Roger"); // returns "Jo Dyne Ro**r"