I want to get the integer in this string xyzabc123.
2 Answers
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);
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);
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.