Jerry Svensson Jerry Svensson - 5 months ago 27
jQuery Question

Regex to remove decimals correctly

I'm trying to create a regex that leaves just numbers from the below numbers. The output should be:

1000
1000
10000
10000


The problem is that the regex for removing decimals also removes all the zeros from the first number, leaving a single number.

Fiddle:

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

Script:

$("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>

Answer

Remove . from string if it follows more than two decimal digits.

$("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>


Regex explanation.

Regular expression visualization

Comments