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);
gyre
  • 16,369
  • 3
  • 37
  • 47
jshill103
  • 320
  • 1
  • 10
  • 1
    Possible duplicate of [How to replace all occurrences of a string in JavaScript?](http://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – gyre Mar 09 '17 at 05:17

6 Answers6

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"
Community
  • 1
  • 1
gyre
  • 16,369
  • 3
  • 37
  • 47
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
buræquete
  • 14,226
  • 4
  • 44
  • 89
1

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

s = s.replace(/[^0-9.]/g, "");
Sangbok Lee
  • 2,132
  • 3
  • 15
  • 33
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);
buræquete
  • 14,226
  • 4
  • 44
  • 89
Jai
  • 74,255
  • 12
  • 74
  • 103
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);
buræquete
  • 14,226
  • 4
  • 44
  • 89
m87
  • 4,445
  • 3
  • 16
  • 31
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, ""));
shizhz
  • 11,715
  • 3
  • 39
  • 49