1

次のような多数のテキスト文字列を含むページがあります。

[1 item here]
Blah blah 99 bottles of beer
[2 items here]
blah [9 items here]

単純なアラートとして合計 (12) を取得する方法を探しています。

the_magic_number= 'me no habla regex'
alert (the_magic_number);
4

1 に答える 1

3

これを行う適切な方法:

var re = /\[(\d+) items? here\]/g,
    sum = 0,
    arr;
while ((arr = re.exec(str)) !== null) {
    sum += parseInt(arr[1]);
}

replaceここでの機能の乱用:

var sum = 0;
str.replace(/\[(\d+) items? here\]/g, function ($0, $1) {
    sum += parseInt($1);
    return ''; // Can return anything, since we don't care about the replace
});
于 2013-04-30T04:19:18.653 に答える