jshill103
jshill103

Reputation: 320

String.replace regex is not replacing `*` in string

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

Upvotes: 0

Views: 393

Answers (6)

Jai
Jai

Reputation: 74738

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

Upvotes: 1

m87
m87

Reputation: 4523

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

Upvotes: 1

gyre
gyre

Reputation: 16777

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"

Upvotes: 4

buræquete
buræquete

Reputation: 14698

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

Upvotes: 1

shizhz
shizhz

Reputation: 12531

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

Upvotes: 0

Sangbok  Lee
Sangbok Lee

Reputation: 2228

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

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

Upvotes: 1

Related Questions