Reputation: 7
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
Upvotes: 0
Views: 203
Reputation:
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);
Upvotes: 2
Reputation: 63524
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);
Upvotes: 0
Reputation: 128
Change the regex statement to match the -
, this can be like so:
/\s*-\d+[.,]\d+/g
Upvotes: 0