Simple javascript regex for strip of numbers

All I want is to remove all numbers from the string.

So,

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

Which clearly gives "bar1" because I indicated only one digit. So why this does not work:

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

What gives "bar01"

+5
source share
4 answers

You must add an option. global

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

It’s clear that 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 speed difference will be very very small if you do not parse the megabytes of text)

If you want to test http://jsperf.com/replace-digits , the second one is apparently faster for blob of 10 digits and large texts.

+12
source

, g: foo.replace(/\d/g,'')

+2
alert(foo.replace(/\d+/g,''));
+2

"global":

foo.replace(/\d*/g,'')

+1
source

All Articles