2013-04-30 55 views
1

从字符串相加或数字我有类似于这种大量的文本字符串的页面:jQuery的获得

[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); 
+0

尝试'document.body.textContent.match(/ \ [(\ d +)项目在这里\]/G);'把所有匹配的字符串 – Ian 2013-04-30 04:05:58

+0

那岂不是 “哟没有hablo正则表达式”。 – Blender 2013-04-30 04:14:02

+1

@Blender显然没有habloEspañoltambien – 2013-04-30 04:14:36

回答

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 
});