最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Extract number from string and assign it to a variable - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 6

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);

发布评论

评论列表(0)

  1. 暂无评论