Javascript 从div类内容的所需位置提取数字,并使用jQuery和regex对其求和
我需要从具有特定类名的div中获取数字并求和。 代码示例如下所示:Javascript 从div类内容的所需位置提取数字,并使用jQuery和regex对其求和,javascript,jquery,regex,count,numbers,Javascript,Jquery,Regex,Count,Numbers,我需要从具有特定类名的div中获取数字并求和。 代码示例如下所示: <div class="refineItem plz3">38440 (19)</div> <div class="refineItem plz3">38444 (4)</div> <div class="refineItem plz3">31993 (6)</div> 3844
<div class="refineItem plz3">38440 (19)</div>
<div class="refineItem plz3">38444 (4)</div>
<div class="refineItem plz3">31993 (6)</div>
38440(19)
38444 (4)
31993 (6)
例如,我想在这里得到所有最新的数字19,4,6,然后对它们求和(sum=29)。您可以使用循环遍历所有元素和regex
从字符串中提取数字
请参见代码中的内联注释:
var total = 0; // Initialize to zero
// For all the elements having refineItem class
$('.refineItem').each(function() {
total += parseInt($(this).text().match(/\((\d+)\)/)[1], 10) || 0; // Use zero when no matching number
});
$('#myInput').val(total); // Update the value of textbox
正则表达式解释
/
:正则表达式的分隔符\(
:匹配文字(
\)
:匹配文字)
()
:捕获组\d+
:匹配一个或多个数字var count = 0;
$('.refineItem').each(function() {
count += parseInt($(this).text().split("(")[1].split(")")[0]);
});
alert(count);
使用JQuery,您可以使用提供的类名迭代每个div,还可以获取写入div中的文本,然后使用match函数从该文本中获取数字并将其转换为数字,以便将其添加到变量中并获得输出
var total = 0;
$(".refineItem").each(function(){
total += Number(Number($(this).text().trim().match(/\((\d+)\)/)[1]));
});
或
您还可以在JSFIDLE上检查这个示例
您尝试了什么?请解释您的答案,以便其他读者更清楚地了解。
var total = 0;
$(".plz3").each(function(){
total += Number(Number($(this).text().trim().match(/\((\d+)\)/)[1]));
});