I have a string in JavaScript like #box2
and I just want the 2
from it.
I tried:
var thestring = $(this).attr(\'href\');
var
Tried all the combinations cited above with this Code and got it working, was the only one that worked on that string -> (12) 3456-7890
var str="(12) 3456-7890";
str.replace( /\D+/g, '');
Result: "1234567890"
Obs: i know that a string like that will not be on the attr but whatever, the solution is better, because its more complete.
you may use great parseInt method
it will convert the leading digits to a number
parseInt("-10px");
// will give you -10
I think this regular expression will serve your purpose:
var num = txt.replace(/[^0-9]/g,'');
Where txt
is your string.
It basically rips off anything that is not a digit.
I think you can achieve the same thing by using this as well :
var num = txt.replace(/\D/g,'');
Using match function.
var thenum = thestring.match(/\d+$/)[0];
alert(thenum);
jsfiddle
And this is a snippet which extracts prices with currency and formatting:
var price = "£1,739.12";
parseFloat(price.replace( /[^\d\.]*/g, '')); // 1739.12
Use this one-line code to get the first number in a string without getting errors:
var myInt = parseInt(myString.replace(/^[^0-9]+/, ''), 10);