bos570
bos570

Reputation: 1523

Regex to mask input for SSN as ***-**-xxxx

I'm trying to mask an input field for a social security number to only show the last 4 digits and mask the rest with an "*". I want the masked number to look something like this

***-**-1234

I have been able to format it to replace all but last 4 with "*" but can't figure out how to additionally add the "-" in the number to follow the ssn format.

const TestComp = () => {
    const [ssn, setSsn] = React.useState(""); 

    return (
    <div>
      <input type="text" value={formatSsn(ssn)} onChange={ e => setSsn(e.target.value)}/>
    </div>
  )
}

const formatSsn = (ssn: string | null | undefined) => {
  return !ssn ? "" : ssn.replace(/[^\d\*]/g, "").replace(/(?=\d{5})\d/, "*");
};

ReactDOM.render(<TestComp />, document.querySelector("#app"))

Here's my jsfiddle with what I have so far.

Upvotes: 3

Views: 2676

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627101

You can use

const formatSsn = (ssn: string | null | undefined) => {
  return !ssn ? "" : ssn.length > 11 ? ssn.substr(0,11) : ssn.replace(/[^\d*]/g, "").replace(/(?=\d{5})\d/, "*")
   .replace(/^(.{1,3})(.{1,2})?(.{1,4})?.*$/, (_,x,y,z) =>
    x + (y ? `-${y}` : '') + (z ? `-${z}` : ''));
};

Notes:

  • If the ssn is longer than 11 chars, just return the first 11 chars
  • .replace(/^(.{1,3})(.{1,2})?(.{1,4})?.*$/, (_,x,y,z) => x + (y ? `-${y}` : '') + (z ? `-${z}` : '') will format the number as expected, two hyphens will be added after the first three chars and after the first five chars (if present).

Upvotes: 2

Related Questions