views:

107

answers:

5

If I have this string

str = "22px";

How do I extract just the number 22? Thanks.

+6  A: 

You could try str.match(/\d+/);

Chris Gutierrez
A better solution than mine... I would of suggested this route if I was up to stuff on my reg expressions...
Ryan
Thanks, wheres the best place to learn reg expressions for javascript?
usertest
A pretty good site is regular-expressions.info. It also has a javascript regex tester. http://www.regular-expressions.info/javascriptexample.html
Chris Gutierrez
A: 

Try this...

parseInt("22px");
Ryan
A: 
"22px".substring(0,2); // returns "22"

But this only works if the number has always 2 digits.

Lenni
A: 

i think you can just go str.substring(0, 2)

Ridz
Like Lenni said, it only works when there are 2 digits.
Jacob Relkin
+4  A: 

If you want an actual number, you should try parseInt(). It will take care of taking off the 'px' for you.

str = "22px";

num = parseInt(str, 10); // pass in the radix for safety :)

assert(num === 22);
Alex Sexton