如何从单个数组项中提取多个整数

时间:2014-05-28 09:32:19

标签: javascript arrays regex function

有人在这里请告诉我修改下面的正则表达式的方法,这样我就能用它获得每个数组项的多个整数吗?我可以使用\ d +检测一个整数,如下面最顶层的str。但是,该函数会在其下面的str = "7yes9 Sir2"等其他两个示例中出错。谢谢。

//str = "10 2One Number*1*";
//output -> [10, 2One, Number*1*] -> [10 + 2 + 1] -> 13

var str = "7Yes9 Sir2";  
//output -> NaN

//var str = "8pop2 1";
//output -> NaN

function NumberAddition(str) {  
  input = str.split(" ");  
  var finalAddUp = 0;  
  var finalArr = [];  

  for(var i = 0; i<=input.length-1; i++) {  
    var currentItem = input[i];  
    var regexp = /(\d+)/g;  
    finalArr.push(Number(currentItem.match(regexp)));  
    var itemToBeCounted = +finalArr[i];  
    finalAddUp += itemToBeCounted;  
  }  
  return finalAddUp;  
}  

console.log(NumberAddition(str));  

1 个答案:

答案 0 :(得分:0)

试试吧。像

<强> HTML

<span id="res"></span>

<强> JS

var str = "7Yes9 Sir2";  
var matches = str.match(/\d+/g);
var res=0;

for (var i=0; i< matches.length; i++) {
    res += parseInt(matches[i],0);
}

$('#res').html(res);

查看此工作fiddle