1

I want to get the integer in this string xyzabc123.

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);
3
  • what is the ending g in your regular expression Commented Feb 2, 2011 at 6:29
  • @Web Developer Global match flag.
    – alex
    Commented Feb 2, 2011 at 6:39
  • @Web Developer It will keep matching to the end of the string, not on first match.
    – alex
    Commented Feb 2, 2011 at 7:00
1

to add to alex's answer if you wanted to get a functional integer

var number = 'xyzabc123'.replace(/[^\d]+/, '');
number = parseInt(number,10);
3
  • What do you mean by a functional integer?
    – alex
    Commented Feb 2, 2011 at 5:57
  • 2
    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). Commented Feb 2, 2011 at 5:58
  • 3
    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. Commented Feb 2, 2011 at 6:02

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.