1

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

2 Answers 2

4

You can replace everything that is not a number with a regex...

var number = 'xyzabc123'.replace(/[^\d]+/g, '');

See it on jsFiddle.

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
Sign up to request clarification or add additional context in comments.

3 Comments

what is the ending g in your regular expression
@Web Developer Global match flag.
@Web Developer It will keep matching to the end of the string, not on first match.
1

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

3 Comments

What do you mean by a functional integer?
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).
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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.