12

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>

3 Answers 3

25

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, "");
Sign up to request clarification or add additional context in comments.

2 Comments

but anyway, here, knock yourself out: regular-expressions.info/refquick.html
Downvoted for the unnecessarily rude commentary. In this case, .replace() is a Javascript method developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… that shouldn't be confused with the jQuery methods api.jquery.com/replaceAll and api.jquery.com/replaceWith
3
var symbol = $("div.price > h5 > div.num").text().replace(/\d+\.?\d+/, "");

1 Comment

Unfortunately this doesn't match 12 without any decimal places. Can't always assume you'll have a consistent input.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.