I'm trying to achieve the following match
Input
123-45-6789
123456789
1234
Reg Ex(s) Tried with output:
\d{5}
123-45-6789
123456789
1234
\d{2,3}
123-45-6789
123456789
1234
\d{3}-{0,1}\d{2}
123-45-6789
123456789
1234
I need to supply this regex to replace method, and I don't want the "-" to be replaced, it should only replace the first 5 digits without changing the format:
Expected Output
123-45-6789
123456789
1234
EDIT
In the above sample outputs:
1> all are matched with global regex 2> the bolded digits are only expected to be matched
The Purpose
I need to mask SSN, eg: 444-55-6666 becomes ###-##-6666 and 444556666 becomes #####6666. Without hampering the format.
match(/(\d{5})/g);
replace(/\D/g, ''); which removes all non-digit characters, including the "." What do I need to do to keep that?
Match a white space followed by one or more decimal digits, followed by zero or one period or comma, followed by zero or more decimal digits. This is the first capturing group. Because the replacement pattern is $1 , the call to the Regex. Replace method replaces the entire matched substring with this captured group.
The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. Something like ^[2-9][1-6]$ matches 21 or even 96! Any help would be appreciated.
You want to match and replace those first five digits:
var str = `123-45-6789
123456789
1234
`
console.log(str.replace(/^(\D*\d\D*){5}/gm, function(match) {
return match.replace(/\d/g, '*');
}))
Here's other ways of looking at it:
You want to ignore all non-numeric characters, and then get the first five numbers
input.replace(/\D/g,'').substr(0,5);
You want to match five numeric characters, wherever they may appear in the input
input.match(/\d/g).slice(0,5);
There is almost always more than one way to approach a problem. If you can't figure out how to do what you want, try re-wording the problem until you find something you can do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With