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

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

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 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