user924035
user924035

Reputation: 41

find and remove character within label text string with jquery

I have this code

<div class="new">
<label> text text text (=price) </label>
</div>

I want to remove the "(=" and ")" around the price,

I've tried the following but to no avail:

 jQuery(document).ready(function() {
     jQuery(".new label").each(function() {
         jQuery(this).text(jQuery(this).text().replace(/[(=]/, ""));
     });
 });

Upvotes: 1

Views: 4677

Answers (4)

bricker
bricker

Reputation: 8941

Nobody has mentioned the 'g' flag, which will replace everything globally:

 $(".new label").each(function() {
   $(this).text($(this).text().replace(/[\)\(=]?/g, ""));
 });

You also needed to escape the parentheses.

http://jsfiddle.net/DdbDQ/1/

edit I won't delete this answer, but it shouldn't be used, because now that I re-read it, it's obvious that it will replace any parentheses or equals signs in the entire label's text. Use Ben Lee's solution.

Upvotes: 0

JMax
JMax

Reputation: 26601

This jsfiddle will match the regexp and replace the content with price (in my example, but you could do whatever you want).

Here is the js:

jQuery(document).ready(function() {
     jQuery(".new label").each(function() {
         jQuery(this).text(jQuery(this).text().replace(/\(=([A-z]*)\)/, "$1"));
     });
 });

Explanation

  • The regexp will match every string matching alpha characters (upcase and lower case >> [A-z]).
  • This string must be surrounded by parenthesis and begin with equal: \(= and /) (don't forget to escape parenthesis)
  • The matched string is used for replacement $1 (this is the first set between parenthesis (...))

See Alternation and grouping paragraph on this page

Upvotes: 0

Ben Lee
Ben Lee

Reputation: 53349

I think your regex pattern is off. Try this:

jQuery(this).text(jQuery(this).text().replace(/\(=(.*?)\)/, "$1"));

Upvotes: 5

Richard Dalton
Richard Dalton

Reputation: 35793

 jQuery(".new label").each(function() {
     jQuery(this).text(jQuery(this).text().replace("(=", "").replace(")", ""));         
 });

This assumes that (= and ) wont appear anywhere else in the label.

http://jsfiddle.net/HcqQC/

Upvotes: -1

Related Questions