askon
askon

Reputation: 671

How to wrap price in span regexp?

I'm trying to wrap the price of an item in a span. Right now the RegExp wraps the numbers but not the $ (dollar sign). I need a regex that wraps the entire price.

HTML
<fieldset>
  <label>
   <input>Thing $4.99</input>
  </label>
</fieldset>

JQUERY
    var rxp = new RegExp("([0-9]+\.?[0-9]+)", "gm");
      $( "fieldset label" ).each(function() {                
        var $this = $(this);
        var content = $this.html();
        console.log($(this).html());
        $this.html(content.replace(rxp, "<span>$1</span>"));
      });

Upvotes: 0

Views: 169

Answers (1)

Eugene Tsakh
Eugene Tsakh

Reputation: 2879

This is not the correct way to do it. html() method will return you html markup, but changing it will not change the DOM. Instead you should empty your parent and append new span in it. Also you are using input tag in a wrong way, it can't have children, you should set value to value attr:

// HTML
<fieldset>
  <label>
   <input value="Thing $4.99" />
  </label>
</fieldset>

// JavaScript
var priceRegExp = /^.*(\$[0-9](\.[0-9]{2})?).*$/;
$("fieldset label").each(function() {                
  var $this = $(this);
  var inputVal = $this.children('input').prop('value');
  var price = priceRegExp.exec(inputVal)[1];
  $this.empty().append('span').text(price);
});

Upvotes: 2

Related Questions