Ozrix
Ozrix

Reputation: 3515

String to number, including non number characters

Is there a native method to convert a string that includes non number characters to a number in one pass, without resorting to str.substring() and then parseInt()?

For example if I would want to convert the string x1 to 1.

Upvotes: 0

Views: 52

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382514

Not one native function, but it's simple enough for positive integers:

var number = +str.match(/\d+/);

If you want to accept a dot and a sign, you may use

var number = +str.match(/-?\d+(?:\.\d*)?/);

Note that this makes 0 if there's no digit in the string.

Upvotes: 3

Related Questions