Javascript 计算字符串中整数的个数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7657824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:04:49  来源:igfitidea点击:

Count the number of integers in a string

javascriptjquery

提问by David

how can I count the number of integers in a string using jQuery or javascript?

如何使用 jQuery 或 javascript 计算字符串中整数的数量?

For example g66ghy7 = 3

例如 g66ghy7 = 3

回答by Petar Ivanov

alert("g66ghy7".replace(/[^0-9]/g,"").length);

Look here.

这里

回答by Ricardo Tomasi

I find this to look pretty/simple:

我觉得这看起来很漂亮/简单:

var count = ('1a2b3c'.match(/\d/g) || []).length

A RegExp will probably perform better (it appears):

RegExp 可能会表现得更好(看起来):

var r = new RegExp('\d', 'g')
  , count = 0

while(r.exec('1a2b3c')) count++;

回答by cillierscharl

The simplest solution would be to use a regular expression to replace all butthe numeric values and pull out the length afterwards. Consider the following:

最简单的解决办法是使用正则表达式替换所有,但该数值,之后拉出长。考虑以下:

var s = 'g66ghy7'; 
alert(s.replace(/\D/g, '').length); //3

回答by scessor

A little longer alternative is to convert each char to a number; if it doesn't fail, raise the counter.

更长的替代方法是将每个字符转换为数字;如果没有失败,请提高计数器。

var sTest = "g66ghy7";

var iCount = 0;
for (iIndex in sTest) {
    if (!isNaN(parseInt(sTest[iIndex]))) {
        iCount++;
    }
}
alert(iCount);

Also see my jsfiddle.

另请参阅我的jsfiddle