Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 417
user1576748 Avatar asked Apr 03 '14 19:04

user1576748


2 Answers

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

like image 148
adeneo Avatar answered Sep 28 '22 01:09

adeneo


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

like image 44
Christopher Bales Avatar answered Sep 28 '22 01:09

Christopher Bales