Beginner
Beginner

Reputation: 9095

replace the few characters from first and last of string

replacing the first and last few characters with the * character, i am able to solve the str1 case. How can i solve the remaining one. Right now i am able to mask the last 4 characters.

how can i mask the first 3 or 4 characters. ? whats wrong in the regex pattern

var str1 = "1234567890123456";
str1 = str1.replace(/\d(?=\d{4})/g, "*");

console.log(str1)

var str2 = "123-456-789-101112"
str2 = str2.replace(/\d(?=\d{4})/g, "*");

console.log(str2) // expected ***-***-***-**1112

var str3 = "abc:def:12324-12356"
str3 = str3.replace(/\d(?=\d{4})/g, "*");

console.log(str3) // expected ***:***:*****-*2356

Right now it is masking only the four characters from last, how can i mask 4 characters from front also like

1234567890123456 => 1234********3456
123-456-789-101112 => 123-4**-***-**1112
abc:def:12324-12356 => abc:d**:*****-*2356

Upvotes: 0

Views: 88

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370639

One option is to lookahead for non-space characters followed by 4 digits. Since you want to replace the alphabetical characters too, use a character set [a-z\d] rather than just \d:

const repl = str => console.log(str.replace(/[a-z\d](?=\S*\d{4})/g, "*"));

repl("1234567890123456");
repl("123-456-789-101112");
repl("abc:def:12324-12356");

If you want to keep the first 4 alphanumeric characters as well, then it's significantly more complicated - match and capture the first 4 characters, possibly interspersed with separators, then capture the in-between characters, then capture the last 4 digits. Use a replacer function to replace all non-separator characters in the second group with *s:

const repl = str => console.log(str.replace(
  /((?:[a-z\d][-@.:]?){4})([-@:.a-z\d]+)((?:[a-z\d][-@.:]?){4})/ig,
  (_, g1, g2, g3) => g1 + g2.replace(/[a-z\d]/ig, '*') + g3
));

repl("1234567890123456");
repl("123-456-789-101112");
repl("abc:def:12324-12356");
repl("[email protected]");

Upvotes: 2

Related Questions