最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript regex, replace all characters other than numbers - Stack Overflow

programmeradmin5浏览0评论

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
Add a comment  | 

6 Answers 6

Reset to default 69

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, "");

\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
发布评论

评论列表(0)

  1. 暂无评论