JavaScript 使用正则表达式提取字符串中的数字

问题描述 投票:0回答:2

我以下面的字符串为例:

var str = "3,000, 2000, 1,000"

我想使用正则表达式提取

3000, 2000, 1000
str.match(/\d+/g)
但结果是错误的:

['3', '000', '2000', '1', '000']

有人可以帮忙吗?谢谢

javascript regex string-formatting number-formatting
2个回答
0
投票

不需要正则表达式。只需按

" "
拆分,从结果中删除所有
,
并将其解析为数字。

var str = "3,000, 2000, 1,000";
var nums = str.split(" ").map(x => +x.replaceAll(",", ""))
console.log(nums)


0
投票

我的答案:

const str = "3,000, 2000, 1,000"
const patt = /(\d+(\,)?)+\d+/g;
const res = (str.match(patt)).map(ele=> +ele.replace(/\,/g, ""))
console.log(res)
© www.soinside.com 2019 - 2024. All rights reserved.