Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple javascript regular expression to strip numbers

All I want is to strip all the numbers from a string.

So

var foo = "bar01";
alert(foo.replace(/\d/,''));

Which obviously gives "bar1" because I've only specified one digit. So why doesn't this work:

var foo = "bar01";
alert(foo.replace(/\d*/,''));

Which gives "bar01"

like image 659
joedborg Avatar asked Oct 21 '11 09:10

joedborg


2 Answers

You must add the global option

var foo = "bar01";
alert(foo.replace(/\d/g,''));

Clearly you can even do something like

var foo = "bar01";
alert(foo.replace(/\d+/g,''));

but I don't know if it will be faster (and in the end the difference of speed would be very very very small unless you are parsing megabytes of text)

If you want to test http://jsperf.com/replace-digits the second one seems to be faster for "blobs" of 10 digits and big texts.

like image 188
xanatos Avatar answered Nov 07 '22 03:11

xanatos


You probably want to specify the g flag: foo.replace(/\d/g,'')

like image 23
duri Avatar answered Nov 07 '22 05:11

duri