Home > Software engineering >  Javascript Remove Negative Decimal Value From String
Javascript Remove Negative Decimal Value From String

Time:05-06

I am trying to remove the negative and positive decimal value from the string following script remove the positive decimal value from the string however negative is not working

var string = "Test Alpha -0.25 (1-3)"
string = string.replace(/\s*\d [.,]\d /g, "");
console.log(string);

above code is returning following output:

Test Alpha - (1-3)

Expected output:

Test Alpha (1-3)

Please help me

CodePudding user response:

You need add the "-" in the regrex condition.

var string = "Test Alpha -0.25 (1-3)"
string = string.replace(/\s*-\d [.,]\d /g, "");
console.log(string);

CodePudding user response:

The sign should be optional (?), and then you can match a set of numbers followed by a . or a ,, followed by another set of numbers, and replace that match. That way you can match both positive and negative numbers with the same expression.

var string = "Test Alpha 0 -0.25 12,31 31 -123.45 (1-3)"
string = string.replace(/( -?\d ([.,]\d )?)/g, '');
console.log(string);

CodePudding user response:

Change the regex statement to match the -, this can be like so:

/\s*-\d [.,]\d /g

  • Related