Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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).
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!