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 class="biguns">
<div class="num">
€12.28
</div>
Lowest Price Per Night
</h5>
</div>
Find and replace text using regular expressions When you want to search and replace specific patterns of text, use regular expressions. They can help you in pattern matching, parsing, filtering of results, and so on. Once you learn the regex syntax, you can use it for almost any language.
Wildcard or regular expressions can also be used with jQuery selector for id of element.
To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
var symbol = $("div.price > h5 > div.num").text().replace(/\d+\.?\d+/, "");
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, "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With