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);
-
-
-
@Web Developer It will keep matching to the end of the string, not on first match.– alexCommented Feb 2, 2011 at 7:00
to add to alex's answer if you wanted to get a functional integer
var number = 'xyzabc123'.replace(/[^\d]+/, '');
number = parseInt(number,10);
-
-
2I 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). Commented Feb 2, 2011 at 5:58
-
3you should always use a radix with parseInt, e.g.
parseInt(number, 10)
otherwise some numbers, beginning with 0 for example, will be converted incorrectly. Commented Feb 2, 2011 at 6:02