简体   繁体   中英

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

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 [az\\d] rather than just \\d :

 const repl = str => console.log(str.replace(/[az\\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( /((?:[az\\d][-@.:]?){4})([-@:.az\\d]+)((?:[az\\d][-@.:]?){4})/ig, (_, g1, g2, g3) => g1 + g2.replace(/[az\\d]/ig, '*') + g3 )); repl("1234567890123456"); repl("123-456-789-101112"); repl("abc:def:12324-12356"); repl("test@test.com"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM