Home > Article > Web Front-end > How to Encode HTML Entities in JavaScript for Consistent User-Generated Content Display?
Encode HTML Entities in JavaScript
When working with user-generated content, entities like ®, &, ©, and ™ may not display consistently across browsers. JavaScript provides several methods for encoding these entities in HTML.
Converting to HTML Entities
To convert a symbol to its corresponding HTML entity, use this code:
<code class="js">var encodedStr = rawStr.replace(/[\u00A0-\u9999<>\&]/g, function(i) { return '&#'+i.charCodeAt(0)+';'; });</code>
Displaying as Superscript
To display the encoded entity as a superscript with custom styling, use CSS:
<code class="css">sup { font-size: 0.6em; padding-top: 0.2em; }</code>
Example Implementation
<code class="js">var regs = document.querySelectorAll('®'); for (var i = 0, l =regs.length; i < l; ++i ) { var div = document.createElement('sup'); var text = document.createTextNode(encodedStr); div.appendChild(text); regs[i].parentNode.insertBefore(div); }</code>
This code:
Additional Considerations
Documentation
The above is the detailed content of How to Encode HTML Entities in JavaScript for Consistent User-Generated Content Display?. For more information, please follow other related articles on the PHP Chinese website!