Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 class="biguns">
    <div class="num">
      €12.28
    </div>
    Lowest Price Per Night
  </h5>
</div>
like image 323
holden Avatar asked Oct 08 '10 12:10

holden


People also ask

Can you replace text with regex?

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.

Can I use regex in jQuery selector?

Wildcard or regular expressions can also be used with jQuery selector for id of element.

How replace text using regex explain with example?

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.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.


2 Answers

var symbol = $("div.price > h5 > div.num").text().replace(/\d+\.?\d+/, "");
like image 81
Ruel Avatar answered Oct 05 '22 00:10

Ruel


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, "");
like image 21
mck89 Avatar answered Oct 05 '22 00:10

mck89