开发者

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

开发者 https://www.devze.com 2023-01-19 10:13 出处:网络
In the example below, the text is selected using jQuery.How can we isolate the currency by getting rid of the other data?

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

精彩评论

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