You can use a regular expression to match social security numbers in a string in JavaScript.
index.tsx178 chars6 lines
In the example above, we use the regular expression /\b\d{3}-\d{2}-\d{4}\b/
to look for a social security number pattern. This pattern looks for 3 digits, a hyphen, 2 digits, another hyphen, and 4 digits. The \b
at the beginning and end of the pattern are word boundaries to ensure that we match only complete social security numbers.
We then use text.match(ssnRegex)
to find the first match of the social security number pattern in the text. This returns an array of matches. Since we only want the first match, we can get it by accessing the [0]
element of the array.
Finally, we log the social security number to the console with console.log(ssn)
.
This method will find the first social security number in the string. If there are multiple social security numbers in the string, you can use a loop and the regex.exec()
method to find all matches.
gistlibby LogSnag