0

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

3
  • 1
    try matching a - ... like /\s*-?\d+ etc Commented May 6, 2022 at 9:26
  • is the structure always the same? like your string = String Number Number ? Commented May 6, 2022 at 9:28
  • thank you /\s*-?\d+[.,]\d+/g this pattern works @Bravo Commented May 6, 2022 at 9:30

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

thank you how to remove 0 example Test Alpha 0 (1-3)?
0

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

2 Comments

hi andy thank you how to remove 0 example Test Alpha 0 (1-3)
@DocuStack Updated. Just make everything from the decimal point a new group, and make that optional too.
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.