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

281
Visualizações
Regex To Find negative number in javascript

I am trying to solve below issue using javascript , let me know if someone came across similar problem and any pointer will be really helpful.

I am working on Currency format where different country can different representation for negative currency format.

Requirement : If a number start /end with - consider such value as negative. Similarly if a number start / end with () consider such value as negative.

-123.55 = > Negative True 
123.55 = > Negative False 
(123.55) => Negative True

My code:

console.log('1234,56' + ' vs ' + formatNumber('1234,56', '', ','));
console.log('1234.56' + ' vs ' + formatNumber('1234.56', '', '.'));
console.log('-1,234.567' + ' VS ' + formatNumber('-1,234.567', ',', '.'));
console.log('1,234.567-' + ' VS ' + formatNumber('1,234.567-', ',', '.'));
console.log("1'234,567-" + " VS " + formatNumber("1'234,567-", "'", ','));
console.log("1'234.567-" + " VS " + formatNumber("1'234.567-", "'", '.'));
console.log("1.234,567-" + " VS " + formatNumber("1.234,567-", ".", ','));

function formatNumber(sourceString, groupseperator, decimalSeperator) {
  let negativeNumber = false;

  var negRegexp = new RegExp("[-|)]$", "g");
  var match = negRegexp.exec(sourceString);
  if (match && match.length > 0) {
    console.log(match[0]);
    negativeNumber = true;
  }

  //Step1 :Replace braces space from the string
  sourceString = sourceString.replace(/[`\s-()'\]\\\/]/gi, '');
  //Step2 :Replace All Group Seperator with blank
  sourceString = sourceString.replace(new RegExp(`[${groupseperator}]`, 'g'), '');

  //Step 3: Replace decimal seperator with .dot
  //Decimal Seperator will only replace from the last occurance
  sourceString = sourceString.replace(new RegExp(`${decimalSeperator}([^${decimalSeperator}]*)$`), '.$1');
  if (negativeNumber) {
    sourceString = '-' + sourceString;
  }
  //console.log(sourceString);
  //console.log(Number(sourceString));
  return Number(sourceString);
}

If you refer code below scenario is failing .

console.log('-1,234.567' + ' VS '+ formatNumber('-1,234.567',',','.'));

It is returning it as positive number

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

0

negRegexp is wrong. It matches - at the end, but not the beginning.

Use separate alternatives in the regexp for each criteria.

var negRegexp = /^-|-$|^\(.*\)$/;
console.log(negRegexp.test('-123.55')); // Negative True 
console.log(negRegexp.test('123.55')); // Negative False 
console.log(negRegexp.test('(123.55)')); // Negative True
console.log(negRegexp.test("1'234,567-")); // Negative True

The first alternative matches - at the beginning, the second matches - at the end, and the third matches ( at the beginning and ) at the end.

There's no need for the g flag since you're only matching one 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