29

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.

2 Answers 2

48

\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.

Sign up to request clarification or add additional context in comments.

5 Comments

thank you for the explanation maybe I can remember this one for the future, oh wait don't need to do that, "favourited"! :)
Will the string ever have float numbers? If so you need another regex. "str 12.3 or 12,3".replace(/\d+([,.]\d+)?/g)
The string will only have integers. Thank you for that suggestion though.
A word of caution, "-1000".match(/\d+/g); will return "1000" not "-1000".
If anyone tries to use @BrunoLM solution from the comment, mind that there must be a replacement argument, "str 12.3 or 12,3".replace(/\d+([,.]\d+)?/g, '')
4

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

1 Comment

It needs the g flag otherwise it fails on "abc123def456"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.