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, "")
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, "")
Share
Improve this question
asked Feb 16, 2012 at 10:08
Prakash RamanPrakash Raman
13.9k28 gold badges86 silver badges137 bronze badges
6 Answers
Reset to default 69You 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, "");
\D
means “not digit”:
"a100.dfwe".replace(/\D/g, "")
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"
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+/
.
"string@! 134".replace(/[^a-z^0-9]+/g, " ");
this would return "string 134"
Based off of @user3324764's answer - Make a prototype function and convert the number to a number.
String.prototype.extractNumber = function ()
{
return Number(this.replace(/(?!-)[^0-9.]/g, ""));
};
Example:
"123.456px".extractNumber(); // 123.456