使此正则表达式适用于所有数字,即使没有小数



我试图编写一个脚本,获取两个数字之间的负百分比数。 由于一个数字是动态的,并且具有不同的货币、小数等,因此我需要一个正则表达式。它几乎有效,但前两个数字仅在我在数字中添加两位小数 (.00) 时才有效。这是为什么呢?

所有数字的输出应为 33。

提琴:小提琴

.HTML:

<div class="left">
 <em class="price product-card-price">
    €1.000&nbsp;
    <span class="vatstatus">Exclusief BTW</span>
 </em>
 <em class="price product-card-price before">
    1500
 </em>
 <a class="pricebubble"></a>
</div>
<div class="left">
 <em class="price product-card-price">
    1&nbsp;000:-&nbsp;
    <span class="vatstatus">Exclusief BTW</span>
 </em>
 <em class="price product-card-price before">
    1500
 </em>
 <a class="pricebubble"></a>
</div>
<div class="left">
 <em class="price product-card-price">
    10,000.00SEK&nbsp;
    <span class="vatstatus">Exclusief BTW</span>
 </em>
 <em class="price product-card-price before">
    15000
 </em>
 <a class="pricebubble"></a>
</div>
<div class="left">
 <em class="price product-card-price">
    SEK10,000.00&nbsp;
    <span class="vatstatus">Exclusief BTW</span>
 </em>
 <em class="price product-card-price before">
    15000
 </em>
 <a class="pricebubble"></a>
</div>

脚本:

$('.left').each(function() {
var frstCol = parseInt($(this).find('em.price.product-card-price').text().replace(/&nbsp;/g, '').replace(/[^0-9.]|.(?=d{3,})/g, "").replace(/(.d+)+/,''), 10);
var seCol = parseInt($(this).find('em.price.product-card-price.before').text().replace(/[^0-9.]/g, ""), 10);        
var result = 100 - (frstCol / seCol) * 100;
console.log("frstCol: ", frstCol, ", seCol: ", seCol);
$(this).find('a.pricebubble').text(parseInt(result)|| 0);
});

问题是因为.left中的两个em都有相同的类,所以你在frstCol中选取了两者的文本。您应该使用 :first 来限制选择器:

var frstCol = parseInt($(this).find('em.price.product-card-price:first').text().replace(/&nbsp;/g, '').replace(/[^0-9.]|.(?=d{3,})/g, "").replace(/(.d+)+/,''), 10);

更新的小提琴

另请注意,您可以稍微简化代码:

$('.left').each(function() {
    var frstCol = parseInt($(this).find('em.price.product-card-price:first').text().trim().replace(/[^0-9.]|.(?=d{3,})/g, ""), 10);
    var seCol = parseInt($(this).find('em.price.product-card-price.before').text().trim().replace(/[^0-9.]/g, ""), 10);
    var result = parseInt(100 - (frstCol / seCol) * 100, 10);
    $(this).find('a.pricebubble').text(result || 0);
});

最新更新