gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:44:29 25 4
gpt4 key购买 nike

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

所有数字的输出应为 33。

fiddle : JSFIDDLE

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

最佳答案

问题是因为 em .left内具有相同的类,因此您将在 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);

Updated fiddle

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

$('.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);
});

关于javascript - 使此正则表达式适用于所有数字,即使没有小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37807039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com