views:

134

answers:

4

I'm new to using regexp, can someone give me the regexp that will strip out everything but an integer from a string in javascript?

I would like to take the string "http://www.foo.com/something/1234/somethingelse" and get it down to 1234 as an integer.

Thanks

+6  A: 
var str = "something 123 foo 432";

// Replace all non-digits:
str = str.replace(/\D/g, '');

alert(str); // alerts "123432"

In response to your edited question, extracting a string of digits from a string can be simple, depending on whether you want to target a specific area of the string or if you simply want to extract the first-occurring string of digits. Try this:

var url = "http://www.foo.com/something/1234/somethingelse";
var digitMatch = url.match(/\d+/); // matches one or more digits
alert(digitMatch[0]); // alerts "1234"

// or:
var url = "http://x/y/1234/z/456/v/890";
var digitMatch = url.match(/\d+/g); // matches one or more digits [global search]
digitMatch; // => ['1234', '456', '890']
J-P
I'm surprised none of the other answers have used the digit shorthand.
Damien Wilson
@Damien: Is there some reason why we should have? :)
Jonathan Sampson
I editted my question to give more details
SLoret
Thanks for the help, this was perfect.
SLoret
+1  A: 

This is just for integers:

[0-9]+

The + means match 1 or more, and the [0-9] means match any character from the range 0 to 9.

Skilldrick
A: 

Just define a character-class that requires the values to be numbers.

/[^0-9]/g // matches anything that is NOT 0-9 (only numbers will remain)
Jonathan Sampson
Isn't that a negated character class?
Skilldrick
@Skilldrick - Try it online http://www.gskinner.com/RegExr/
Jonathan Sampson
Oh, you're replacing the numbers with nothing, I didn't get that before the comment.
Skilldrick
@Skilldrick - No, I'm replacing the *non-numbers* with nothing :)
Jonathan Sampson
I editted my question to give more details
SLoret
+1  A: 
uri = "http://www.foo.com/something/1234/somethingelse";
alert(uri.replace(/.+?\/(\d+)\/.+/, "$1"))
stereofrog
`uri.replace`? why?
The Elite Gentleman
why what?......
stereofrog