views:

44

answers:

2

Hello all,

How do I remove numbers from a string using Javascript?

I am not very good with regex at all but I think I can use with replace to achieve the above?

It would actually be great if there was something JQuery offered already to do this?

//Something Like this??

var string = 'All23';
string.replace('REGEX', '');

I appreciate any help on this.

+4  A: 

\d matches any number, so you want to replace them with an empty string:

string.replace(/\d+/g, '')

I've used the + modifier here so that it will match all adjacent numbers in one go, and hence require less replacing. The g at the end is a flag which means "global" and it means that it will replace ALL matches it finds, not just the first one.

nickf
@nickf thank you for the explanation maybe I can remember this one for the future, oh wait don't need to do that, "favourited"! :)
Abs
Will the string ever have float numbers? If so you need another regex. `"str 12.3 or 12,3".replace(/\d+([,.]\d+)?/g)`
BrunoLM
The string will only have integers. Thank you for that suggestion though.
Abs
+1  A: 

Just paste this into your address bar to try it out:

javascript:alert('abc123def456ghi'.replace(/\d+/g,''))

\d indicates a character in the range 0-9, and the + indicates one or more; so \d+ matches one or more digits. The g is necessary to indicate global matching, as opposed to quitting after the first match (the default behavior).

Mark Rushakoff
It needs the `g` flag otherwise it fails on "abc123def456"
nickf