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, "")
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.
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.
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.
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.
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, "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With