Prakash Raman
Prakash Raman

Reputation: 13923

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

Upvotes: 31

Views: 135376

Answers (6)

pelume_
pelume_

Reputation: 312

"string@! 134".replace(/[^a-z^0-9]+/g, " ");

this would return "string 134"

Upvotes: 2

Aaron Sherman
Aaron Sherman

Reputation: 3877

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

Upvotes: 0

fanaugen
fanaugen

Reputation: 1127

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+/.

Upvotes: 2

ctay
ctay

Reputation: 419

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"

Upvotes: 8

Andy E
Andy E

Reputation: 344537

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

Upvotes: 69

Molecular Man
Molecular Man

Reputation: 22386

\D means “not digit”:

"a100.dfwe".replace(/\D/g, "")

Upvotes: 24

Related Questions