admin管理员组文章数量:1418627
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);
本文标签: javascriptExtract number from string and assign it to a variableStack Overflow
版权声明:本文标题:javascript - Extract number from string and assign it to a variable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745292405a2651876.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论