逗号分隔字符串的总和

时间:2015-12-05 08:33:24

标签: javascript string sum

我有一个字符串: string ="绿色3,红色5,蓝色6,&#34 ;;

我想将数值加在一起,即这个字符串的答案应该是:3 + 5 + 6 = 14

我已从字符串中删除了无数字值但无法找到添加数字的方法!

var string = string.replace(/ \ D / g,""); 到目前为止,我得到356而不是14!

4 个答案:

答案 0 :(得分: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;
});

答案 1 :(得分:0)

这是一种方法:

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

答案 2 :(得分: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>

答案 3 :(得分: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