user1576748
user1576748

Reputation: 687

How to replace the same character multiple times?

I need to replace a specific character for all elements whose class is the same with jQuery. Consider this html code:

<div class="product-name">
   <h1>Apple®</h1>
</div>

<div class="product-name">
   <h2>iPhone®</h2>
</div>

<div class="product-name">
   <h3>iPhone 5S®</h3>
</div>

I need to replace all the ® charactesr with superscript tags with this code:

$('.product-name').html(
  $('.product-name').html().replace(/®/gi, '<sup>&reg;</sup>')
);

However, this code will replace the first occurrence only. For the second and beyond occurrences, it'll replace the whole product names with the first product name including the h1 tags.

How can I replace just the ® characters without changing the other characters and tags?

Upvotes: 5

Views: 403

Answers (2)

Christopher Bales
Christopher Bales

Reputation: 1071

Try $('.product-name').html().split("®").join('<sup>&reg;</sup>');

For a more complete answer,

var body = $("body").html().split('®').join('<sup>&reg;</sup>');
$("body").html(body);

JS Fiddle

Upvotes: 1

adeneo
adeneo

Reputation: 318352

You can use the callback in html() to return the value to each element in the collection

$('.product-name').html(function(_, html) {
     return html.replace(/®/gi, '<sup>&reg;</sup>')
});

FIDDLE

Upvotes: 4

Related Questions