Reputation: 3515
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
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