'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



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1