aWebDeveloper
aWebDeveloper

Reputation: 38422

String To integer JavaScript

I want to get the integer in this string xyzabc123.

Upvotes: 1

Views: 3040

Answers (2)

jondavidjohn
jondavidjohn

Reputation: 62412

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

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

Upvotes: 1

alex
alex

Reputation: 490637

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);

Upvotes: 4

Related Questions