Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

113
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda