gpt4 book ai didi

javascript - 从字符串中提取数字并将其分配给变量

转载 作者:行者123 更新时间:2023-11-28 16:45:28 31 4
gpt4 key购买 nike

我有“385 KM”,我想使用 JavaScript 删除“KM”并将结果值“385”放入变量中,以便我可以将其用作数字来与另一个数字进行比较。

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

上面的结果是一个数字后跟“KM”,我只想保留这个数字。

最佳答案

您尝试使用 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);

或:您可以将所有非数字替换为空字符串:

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

关于javascript - 从字符串中提取数字并将其分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60610446/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com