Reputation: 768
I need regexp for masking values except for the last 4 characters and spaces.
1234 4567 8901 2345
=> **** **** **** 2345
123445678901 23 4 5
=> ************ 23 4 5
[^\s](?=.{4,}$)
doesn't pass for me
Upvotes: 3
Views: 460
Reputation: 163277
You could update the pattern to assert 4 digits at the right until the end of the string.
\d(?=(?:[ \d]*\d){4}$)
Explanation
\d
match a digit(?=
Positive lookahead
(?:
Non capture group
[ \d]*\d
Match 0+ times a space or digits followed by a single digit){4}$
and repeat that 4 times ans assert the end of the string)
Close lookahead[
"1234 4567 8901 2345",
"123445678901 23 4 5"
].forEach(s => console.log(s.replace(/\d(?=(?:[ \d]*\d){4}$)/gm, "*")));
Upvotes: 0
Reputation: 10384
I'm not sure you need a negative lookahead. If you have control over the input format then try this:
const number = '1234 5678 9012 3456';
const masked = number.replace(/\d{4}\s/g, '**** ');
console.log(masked);
If you want to accept also random spaces, try this:
const number = '1234 5678 9 012 3 45 6';
const masked = number.replace(/(\d\s*){4}\s/g, '**** ');
console.log(masked);
Upvotes: 0
Reputation: 626758
You can use
.replace(/\d(?=.*\d(?:\s*\d){3}\s*$)/g, '*')
See the regex demo
Regex details
\d
- a digit(?=.*\d(?:\s*\d){3}\s*$)
- that is followed with any amount of any chars other than line break chars and then a digit, followed with three occurrences of 0+ whitespaces + a digit and then 0+ whitespaces at the end of string.Upvotes: 1