'Javascript Remove Negative Decimal Value From String
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
Solution 1:[1]
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);
Solution 2:[2]
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);
Solution 3:[3]
Change the regex statement to match the -, this can be like so:
/\s*-\d+[.,]\d+/g
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 | |
| Solution 2 | |
| Solution 3 | Jake |
