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

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

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 Relatório

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