2015-12-05 302 views
3

我有一個字符串: string =「Green 3,Red 5,Blue 6,」;逗號分隔字符串的總和

我想的數值加在一起,也就是回答這個字符串應該是:3 + 5 + 6 = 14

我已刪除從字符串中沒有數值,但無法找到添加數字的方法! var string = string.replace(/ \ D/g,「」); 到目前爲止我得到356而不是14!

+0

'string.match(/ \ d + /克)'然後求和陣列elems的。 –

回答

0
<html> 
<head> 
    <title>Please Rate Me If this helps you...</title> 
    <script> 
    window.onload = function() { 
     var string = "Green 3, Red 5, Blue 6"; 
     var separeted = string.split(","); 
     var sum = 0; 
     for (var i = 0; i < separeted.length; i++) { 
      sum += parseInt(separeted[i].toString().match(/(\d+)/)); 
     } 
     alert(sum); 
    } 
    </script> 
</head> 
<body> 
</body> 
</html> 
+0

Update sum + = separeted [i] .toString()。match(/(\ d +)/)!= null? parseInt(separeted [i] .toString()。match(/(\ d +)/)):0; –

+0

謝謝,它工作! – Alex

+0

這是我的榮幸... –

0

這裏是這樣做的一種方式:

string.split(',').reduce(function(sum, cur) { 
    var n = cur.match(/(\d+)/); 
    return sum + (n && parseInt(n[1],10) || 0); 
}, 0); 
//=> 14 
0

嘗試......希望這將幫助ü

<span id="foo">280ms</span> 
<span>sum:</span><span id="spid"></span> 

var text = $('#foo').text(); 
output = text.split(","), 
var sum = 0; 
    for (var i = 0; i < output.length; i++) { 
     sum += parseInt(output[i].toString().match(/(\d+)/)); 
    } 
$("#spid").text(sum) 

Updated Fiddle

+0

這不適用於所需的輸入'「綠色3,紅色5,藍色6」,「 – Andreas

+0

您的答案中的代碼沒有改變 – Andreas

2

使用string.prototype.matcharray.prototype.reduce

var string = "Green 3, Red 5, Blue 6, " 
var result = string.match(/\d+/g).reduce(function(a,b) {return +a + +b;}); 

其等於

var string = "Green 3, Red 5, Blue 6, " 
var array = string.match(/\d+/g); 
var result = array.reduce(function(a,b) { 
    return +a + +b; 
});