正则表达式正确删除小数

时间:2016-06-14 07:10:46

标签: jquery

我正在尝试创建一个正则表达式,只留下以下数字的数字。输出应为:

1000
1000
10000
10000

问题是删除小数的正则表达式还会从第一个数字中删除所有零,只留下一个数字。

小提琴:

https://jsfiddle.net/28dL2fvp/11/

脚本:

$("em.price.product-card-price").each(function() {
var $this = $(this);
$this.html($this.html().replace(/ /g, '').replace(/[^0-9.]/g, "").replace(/(\.\d+)+/,''), 10);
});

HTML:

<div class="left">
 <em class="price product-card-price">
    €1.000&nbsp;
 </em>
</div>

<div class="left">
 <em class="price product-card-price">
    1&nbsp;000&nbsp;
 </em>
</div>

<div class="left">
 <em class="price product-card-price">
    10,000.00SEK&nbsp;
 </em>
</div>

<div class="left">
 <em class="price product-card-price">
    SEK10,000.00&nbsp; 
 </em>
</div>

1 个答案:

答案 0 :(得分:2)

如果字符串超过两位小数,则从字符串中删除$("em.price.product-card-price").each(function() { var $this = $(this); $this.html($this.html().replace(/&nbsp;/g, '').replace(/[^0-9.]|\.(?=\d{3,})/g, "").replace(/(\.\d+)+/,''), 10); });

$("em.price.product-card-price").each(function() {
  var $this = $(this);
  $this.html($this.html().replace(/&nbsp;/g, '').replace(/[^0-9.]|\.(?=\d{3,})/g, "").replace(/(\.\d+)+/, ''), 10);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="left">
  <em class="price product-card-price">
        €1.000&nbsp;
    </em>

</div>
<div class="left">
  <em class="price product-card-price">
        1&nbsp;000&nbsp;
    </em>
</div>

<div class="left">
  <em class="price product-card-price">
        10,000.00SEK&nbsp;
    </em>

</div>

<div class="left">
  <em class="price product-card-price">
        SEK10,000.00&nbsp; 
    </em>
</div>
intent.putExtra("Name","activity1");

Regex explanation.

Regular expression visualization