0

I have a string that comes in and I am running a string.replace on it and it is not removing the * character from the string but it is removing the | character.

var s = "|*55.6";
s = s.replace(/[^0-9.]/, "");
console.log(s);

1

6 Answers 6

4

Use a global regular expression (/.../g) if you want to replace more than a single match:

s = s.replace(/[^0-9.]+/g, "") //=> "55.6"

Edit: Following your pattern with + (which matches more than one of a pattern in succession) will produce fewer matches and thus make the replacement with "" run more efficiently than using the g flag alone. I would use them both together. Credit to Jai for using this technique in his answer before me.


Demo Snippet

var s = "|*55.6"
s = s.replace(/[^0-9.]+/g, "")
console.log(s) //=> "55.6"

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

Comments

1

It's because replace executed just once. Use g option to replace every match.

s = s.replace(/[^0-9.]/g, "");

Comments

1

You haven't used a global flag for your regex, that is why the first occurrence was replaced, than the operation ended.

var s = "|*55.6";
s = s.replace(/[^\d.]/g, "");
console.log(s);

Using + quantifier alone wouldn't help if you have separate occurrences of [^\d.], though would be better to use together with g flag. For example;

var s = "|*55.6a"
s = s.replace(/[^0-9.]+/, "")
console.log(s) //=> "55.6a not OK

Comments

1

You need to use a global (g) flag / modifier or a plus (+) quantifier when replacing the string;

var s = "|*55.6";
s = s.replace(/[^0-9.]/g, "");
console.log(s);

var s = "|*55.6";
s = s.replace(/[^0-9.]+/, "");
console.log(s);

Comments

1

You are missing + to look for one or more occurrences:

var s = "|*55.6";
s = s.replace(/[^0-9.]+/, "");
console.log(s);

Also if you are interested to takeout the numbers, then you can use .match() method:

var s = "|*55.6";
s = s.match(/[(0-9.)]+/g)[0];
console.log(s);

Comments

0

Some answer mentioned the Quantifiers +, but it will still only replace the first match:

console.log("|*45.6abc".replace(/[^0-9.]+/, ""))

If you need to remove all non-digital chars(except .), the modifier/flag g is still required

console.log("|*45.6,34d".replace(/[^0-9.]+/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.