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

203
Visualizações
Parse a number but keep the negative's in a text box

Here is what I'm trying to do.

Right now I can parse a number by adding commas automatically, however, when I try to type a negative it goes away.

Here is the current code that I'm using to parse the number:

      $(this).val(function(index, value) {
          return value
                .replace(/\D/g, "")
                .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            }); 

How do I keep the number negative value?

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

0

\D matches anything that isn't a decimal digit, so you're removing the minus sign. Use [^-\d] instead to remove anything that isn't a digit or minus sign.

function add_commas(value) {
  return value
    .replace(/[^-\d]/g, "")
    .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

console.log(add_commas('1234567'));
console.log(add_commas('-1234567'));
console.log(add_commas('-123,4X567'));

Caveat: this won't work correctly if they put a - in the middle of the number, since it will be left in the number.

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