I want to get the integer in this string xyzabc123.
alex
492k205 gold badges891 silver badges992 bronze badges
asked Feb 2, 2011 at 5:51
aWebDeveloper
38.7k42 gold badges179 silver badges248 bronze badges
2 Answers 2
You can replace everything that is not a number with a regex...
var number = 'xyzabc123'.replace(/[^\d]+/g, '');
Update
To protect yourself from a string like this: b0ds72 which will be interpreted as octal, use parseInt() (or Number(); Number is JavaScript's number type, like a float.)
number = parseInt(number, 10);
answered Feb 2, 2011 at 5:52
alex
492k205 gold badges891 silver badges992 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
aWebDeveloper
what is the ending g in your regular expression
alex
@Web Developer Global match flag.
alex
@Web Developer It will keep matching to the end of the string, not on first match.
to add to alex's answer if you wanted to get a functional integer
var number = 'xyzabc123'.replace(/[^\d]+/, '');
number = parseInt(number,10);
answered Feb 2, 2011 at 5:53
jondavidjohn
62.5k21 gold badges120 silver badges159 bronze badges
3 Comments
alex
What do you mean by a functional integer?
jondavidjohn
I mean a value of actual integer type, you're example does not convert a string to an integer, it changes a string to a string (of number characters).
Nick Craver
you should always use a radix with parseInt, e.g.
parseInt(number, 10) otherwise some numbers, beginning with 0 for example, will be converted incorrectly.lang-js