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 pare 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.
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 pare 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.
Share Improve this question edited Mar 10, 2020 at 4:03 Mike 1,33710 silver badges18 bronze badges asked Mar 10, 2020 at 1:31 SamSam 791 silver badge9 bronze badges1 Answer
Reset to default 6You 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);