次のような多数のテキスト文字列を含むページがあります。
[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);
次のような多数のテキスト文字列を含むページがあります。
[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);
これを行う適切な方法:
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
});