如何解析JavaScript中字符串中的数字?

时间:2022-01-22 19:33:06

Let's say I have an input field and want to parse all of the numbers from the submitted string. For example, it could be:

假设我有一个输入字段,想要解析提交的字符串中的所有数字。例如,它可能是:

Hi I'm 12 years old.

How do I parse all of the numbers without having a common pattern to work with?

如何在不使用通用模式的情况下解析所有数字?

I tried:

我试过了:

x.match(/\d+/)

but it only grabs the 12 and won't go past the next space, which is problematic if the user inputs more numbers with spaces in-between them.

但它只能抓住12并且不会越过下一个空间,如果用户输入更多带有空格的数字,这就有问题。

2 个解决方案

#1


10  

Add the g flag to return all matches in an array:

添加g标志以返回数组中的所有匹配项:

var matches = x.match(/\d+/g)

However, this may not catch numbers with seperators, like 1,000 or 0.123

但是,这可能无法与分离器捕获数字,如1,000或0.123

You may want to update your regex to:

您可能希望将正则表达式更新为:

x.match(/[0-9 , \.]+/g)

#2


0  

var words = sentence.split(" ");
var numbers = words.filter(function(w) {
    return w.match(/\d+/);
})

#1


10  

Add the g flag to return all matches in an array:

添加g标志以返回数组中的所有匹配项:

var matches = x.match(/\d+/g)

However, this may not catch numbers with seperators, like 1,000 or 0.123

但是,这可能无法与分离器捕获数字,如1,000或0.123

You may want to update your regex to:

您可能希望将正则表达式更新为:

x.match(/[0-9 , \.]+/g)

#2


0  

var words = sentence.split(" ");
var numbers = words.filter(function(w) {
    return w.match(/\d+/);
})