Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从div类内容的所需位置提取数字,并使用jQuery和regex对其求和_Javascript_Jquery_Regex_Count_Numbers - Fatal编程技术网

Javascript 从div类内容的所需位置提取数字,并使用jQuery和regex对其求和

Javascript 从div类内容的所需位置提取数字,并使用jQuery和regex对其求和,javascript,jquery,regex,count,numbers,Javascript,Jquery,Regex,Count,Numbers,我需要从具有特定类名的div中获取数字并求和。 代码示例如下所示: <div class="refineItem plz3">38440&nbsp;(19)</div> <div class="refineItem plz3">38444&nbsp;(4)</div> <div class="refineItem plz3">31993&nbsp;(6)</div> 3844

我需要从具有特定类名的div中获取数字并求和。 代码示例如下所示:

    <div class="refineItem plz3">38440&nbsp;(19)</div>
    <div class="refineItem plz3">38444&nbsp;(4)</div>
    <div class="refineItem plz3">31993&nbsp;(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]));
    });