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>®</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?
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>®</sup>')
});
FIDDLE
Try
$('.product-name').html().split("®").join('<sup>®</sup>');
For a more complete answer,
var body = $("body").html().split('®').join('<sup>®</sup>');
$("body").html(body);
JS Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With