开发者

Using regular expressions (regex) to replace selected text in jQuery / JavaScript

In the example below, the text is selected using jQuery. How can we isolate the currency by getting rid of the other data?

This attempt at using JavaScript's replace did not work:

var symbol = $("div.price > h5 > div.num").text().replace(/[\d.]*/, "");

This is the example HTML; the jQuery selector is working:

<div class="price">
  <h5 clas开发者_运维问答s="biguns">
    <div class="num">
      €12.28
    </div>
    Lowest Price Per Night
  </h5>
</div>


The dot must be escaped othwerwise it will match every character and you must set the global modifier:

var symbol = $("div.price > h5 > div.num").text().replace(/[\d\.]+/g, "");


var symbol = $("div.price > h5 > div.num").text().replace(/\d+\.?\d+/, "");


If the currency is always the first character and it's one character long, you could easily get it with

var symbol = $(".num").text().substr(0,1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜