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

185
Visualizações
Regular expression to insert dash into numbers after 3 and 4 digits

I'm trying to insert dash into numbers but it is so hard to me... What I want to do is that insert dash into after 3 and 4 digits, for example,

replacing 123123412345 to 123-1234-12345.

The additional condition is that I replace it in input element. So I replace the number for every input event, i.e., I need to replace like

1 to 1
12 to 12
123 to 123
1231 to 123-1
...
1231234 to 123-1234
12312341 to 123-1234-1
...
123123412345 to 123-1234-12345

How can I do this using regex ??

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You may try this regex:

  • Regex
(?<=^\d{3}|^\d{7})(?=\d)
  • Substitution
-

Check the proof

const list = [
  1,
  12,
  123,
  1231,
  1231234,
  12312341,
  123123412345
];

const regex = /(?<=^\d{3}|^\d{7})(?=\d)/g;
const result = list.map(e => regex[Symbol.replace](e, '-'));

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

Suppose it needs to split the first 3 next 4 digits only, it can be done with following regexp replacement

str.replace(/((?<!\d)\d{3}(?!\b)|(?<=^\d{3})\d{4}(?!\b))/g, '$1-')

Input string has to be all digits

document.getElementById('input').addEventListener('keyup', (e) => {
e.target.value = e.target.value.split('-').join('').replace(/((?<!\d)\d{3}(?!\b)|(?<=^\d{3})\d{4}(?!\b))/g, '$1-');
});

['1', '12', '123', '1231', '12312', '123123', '1231234', '12312341', '123123412', '1231234123', '12312341234', '123123412345']
.forEach(t => console.log(t.replace(/((?<!\d)\d{3}(?!\b)|(?<=^\d{3})\d{4}(?!\b))/g, '$1-')));
<input id="input" type="text" size="20">

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