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

295
Vistas
Regex - Remove special characters but retain negative numbers

I'm building a Number Stepper component in React which needs to support integers (both positive and negative) and decimal numbers. I want to only hold the numeric part of any possible value in state in order for the arithmetic methods to work correctly.

So:

User enters 5, 5 is stored in state

User enters 5.5, 5.5 is stored in state

User enters £5.57, 5.57 is stored in state

User enters -5, -5 is stored in state

To do this I've been using the following regex within a .replace() to remove any special characters:

value.replace(/[^0-9.]/, '')

However this removes the minus - character from negative values. I have tried adding it to the capture group like this: replace(/[^0-9.-]/, '') but this matches both -5 and 5 - 3. I would like to retain negative numbers but exclude any other use of the minus symbol.

Any ideas?

Thanks

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can use

value.replace(/(-\d*\.?\d+).*|[^0-9.]/g, '')

Details

  • (?!^)- - a hyphen not at the start of string
  • | - or
  • [^0-9.-] - any char other than a digit, dot or hyphen.

const c = ['5', '5.5', '£5.57', '-5', '-5-5', '5-3'];
const re = /(?!^)-|[^0-9.-]/g;
for (var i of c) {
    console.log(i, '=>', i.replace(re, ''));
}

about 4 years ago · Juan Pablo Isaza Denunciar

0

This seems to do what you want:

const trimSpecial = x => x
  // first preserve all `-`
  .replace(/[^0-9.-]/g, '')
  // then remove all `-` except, optionally, the one in first position
  .replace(/(?!^-)-/g, '')

const test = x=>console.log(x, "=>", trimSpecial(x))

test("-5.8")
test("$-3")
test("-5-5")
test("6 - 6")

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