Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex, replace all characters other than numbers

I would like to replace all the characters other than 0-9 in a string, using Javascript.

Why would this regex not work ?

 "a100.dfwe".replace(/([^0-9])+/i, "") 
like image 324
Prakash Raman Avatar asked Feb 16 '12 10:02

Prakash Raman


People also ask

How do I change everything except numbers?

To remove all characters except numbers in javascript, call the replace() method, passing it a regular expression that matches all non-number characters and replace them with an empty string. The replace method returns a new string with some or all of the matches replaced.

How do you replace all occurrences of a character in a string in JavaScript?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

Can regex replace characters?

They use a regular expression pattern to define all or part of the text that is to replace matched text in the input string. The replacement pattern can consist of one or more substitutions along with literal characters. Replacement patterns are provided to overloads of the Regex.

How do you replace letters in JavaScript?

You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.


1 Answers

You need the /g modifier to replace every occurrence:

"a100.dfwe".replace(/[^0-9]+/g, ""); 

I also removed the redundant i modifier and the unused capturing sub-expression braces for you. As others have pointed out, you can also use \D to shorten it even further:

"a100.dfwe".replace(/\D+/g, ""); 
like image 124
Andy E Avatar answered Sep 18 '22 07:09

Andy E