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

246
Visualizações
Is there a regex to replace all occurences except for the first one?

I already tried to use this for above mentioned intention

var str = "48abc5,2d25.,ft87";
str = str.replace(/[^\d(,.)?]/g, '');
console.log(str);

I expected the output would be 485,225 because of the 0-1 condition through the question mark.

However my output is 485,225.,87

Simply my final approach is to have a number seperated by comma or a dot. Following pattern would fit my intention:

{1-9}+{0-9)?{, | . }{1-9}*

Would love to hear your solutions.

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

0

Inside character classes, all chars are literal, except for ^, \, [ and -. So, you cannot add ? there and expect it to behave as a quantifier.

You need

var str = "48abc5,2d25.,ft87";
str = str.replace(/[^\d,.]+/g, '').replace(/^([^.,]*(?:[.,][^.,]*)?).*/, '$1').replace(/^0+/, "");
console.log(str);

The .replace(/[^\d,.]+/g, '') part removes all chars other than digits, dots and commas.

The .replace(/^([^.,]*(?:[.,][^.,]*)?).*/, '$1') part keeps the first steak of digits and optionally a second streak of digits after the first . or ,.

The .replace(/^0+/, "") part removes one or more 0 digits at the beginning of the string.

Your fixed demo fiddle:

function testRegex(event){
    let evt = event || window.event
  console.log(evt.target.value)
  document.getElementById("result").innerHTML = "Result: "+ 
  evt.target.value.replace(/[^\d,.]+/g, '')
                            .replace(/^([^.,]*(?:[.,][^.,]*)?).*/, '$1')
                              .replace(/^0+/, "");
}
<label>Value:</label>
<input onkeyup="testRegex()" type="text"/>
<p id="result">Result:</p>

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