gpt4 book ai didi

javascript - 如何从长字符串中提取数字

转载 作者:行者123 更新时间:2023-11-28 17:39:10 29 4
gpt4 key购买 nike

我有这个字符串,我在我的项目中使用 JavaScript 并且我有这个

338 km 3 heurs 28 minutes

我想要的是仅提取数字,我想创建一个可以将每个数字放入变量中的方法。

我尝试过,但不起作用:

var num = "338 km 3 heurs 28 minutes".match(/[\d]+/g)
var num = "338 km 3 heurs 28 minutes".match(/[\d]+/g)
var num = "338 km 3 heurs 28 minutes".match(/[\d]+/g)

最佳答案

您可以使用array destructuring将每个数字分配给变量或常量。

注意:我正在使用 Array#mapNumber function将每个数字字符串转换为实际数字,但如果您只需要数字字符串,可以跳过此步骤。

const [a, b, c] = "338,7 km 3 heurs 28 minutes"
.match(/\d+(:?,\d+)?/g) // match numbers with commas as decimal separator
.map((n) => Number(n.replace(',', '.'))); // convert the comma to dot, and convert to number

console.log(a);
console.log(b);
console.log(c);

关于javascript - 如何从长字符串中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48358840/

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