Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

112
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda