Anoop
Anoop

Reputation: 23208

How to get numerical value from String containing digits and characters

Is there any built in method to get which can parse int from string ("23px")?

I know I can use substring and then parseInt but I want to know if there is any other way available to do this.

Upvotes: 4

Views: 3939

Answers (2)

RobG
RobG

Reputation: 147373

parseInt will grab the first set of contiguous numbers:

parseInt('23px');

returns 23.

If there is any chance there will be leading zeros, use a radix:

parseInt('23px', 10);

which is a good habit in general.

Upvotes: 8

Marcelo
Marcelo

Reputation: 2302

parseInt can do it. Just use:

var num = parseInt("23px", 10);

It will parse the integer part and ignore the rest.

Upvotes: 3

Related Questions