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);
精彩评论