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.

Abs
  • 56,052
  • 101
  • 275
  • 409

2 Answers2

47

\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
  • 537,072
  • 198
  • 649
  • 721
  • thank you for the explanation maybe I can remember this one for the future, oh wait don't need to do that, "favourited"! :) – Abs May 20 '10 at 22:44
  • 3
    Will the string ever have float numbers? If so you need another regex. `"str 12.3 or 12,3".replace(/\d+([,.]\d+)?/g)` – BrunoLM May 20 '10 at 22:53
  • The string will only have integers. Thank you for that suggestion though. – Abs May 21 '10 at 15:37
  • A word of caution, `"-1000".match(/\d+/g);` will return "1000" not "-1000". – Kumar May 27 '13 at 03:47
  • 1
    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, '')` – Wiktor Stribiżew Oct 18 '17 at 20:16
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).

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398