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, "")
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, "");
parseInt() and parseFloat().What about negative numbers:
Using Andy E's example works unless you have a negative number. Then it removes the '-' symbol also leaving you with an always positive number (which might be ok). However if you want to keep number less than 0 I would suggest the following:
"a-100.dfwe".replace(/(?!-)[^0-9.]/g, "") //equals -100
But be careful, because this will leave all '-' symbols, giving you an error if your text looks like "-a-100.dfwe"
- because it's not at the beginning of the string.It doesn't work because the character class [^0-9] (= anything but digits) with the repetition modifier + will only match one sequence of non-numeric characters, such as "aaa".
For your purpose, use the /g modifier as the others suggest (to replace all matches globally), and you could also use the pre-defined character class \D (= not a digit) instead of [^0-9], which would result in the more concise regex /\D+/.
\D+ says "look for one or more non-digits", whereas (\D)+ looks for one or more repetitions of the (same) non-digit, which is not what you want. Now, whether you do /\D/g (replace every single non-digit), or /\D+/g (replace every sequence of non-digits) doesn’t really matter except possibly in terms of performance, which won’t be noticeable unless you process tens of thousands of strings.[^0-9]+ and ([^0-9])+ will both match the same strings, whether they're aaa or abc. The one with the group just does some unnecessary capturing along the way. The /g flag is the answer.