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

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

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