Sam
Sam

Reputation: 79

Extract number from string and assign it to a variable

I have "385 KM" and I want to use JavaScript to remove " KM" and put the result value "385" in a variable so I can use it as a number to compare it with another number.

var checkDistance = result.routes[0].legs[0].distance.text;

The result of the above is a number followed by " KM" and I want to keep the number only.

Upvotes: 2

Views: 4282

Answers (1)

Mamun
Mamun

Reputation: 68933

You try using parseInt():

The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

var str = "385 KM";
var num = parseInt(str);
console.log(num);

OR: You can replace all the non digits with empty string:

var str = "385 KM";
var numStr = str.replace(/\D/g,'');
console.log(numStr);

Upvotes: 6

Related Questions