Introduction
When displaying user-generated content, it's crucial to handle special characters like ® and &, which may not render correctly in all browsers. To address this, it's necessary to convert these symbols into HTML entities for consistent display.
JavaScript Solution
A straightforward JavaScript approach to encoding HTML entities is to use regular expressions to match the desired symbols and replace them:
<code class="javascript">const encodedStr = rawStr.replace(/[\u00A0-\u9999<>\&]/g, function(i) { return '&#'+i.charCodeAt(0)+';'; });</code>
This code iterates over the given character range (unicode 00A0 - 9999, plus ampersand, greater & less than). For each match, it returns the HTML entity equivalent (nnn;), where nnn is the unicode character code.
Sup Tag Wrapping
If you require the HTML entity to be wrapped in a tag for styling purposes:
<code class="javascript">// First encode the HTML entity as described above. const encodedStr = rawStr.replace(/[\u00A0-\u9999<>\&]/g, function(i) { return '&#'+i.charCodeAt(0)+';'; }); // Then, wrap the encoded entity in a `<sup>` tag: const supEncodedStr = encodedStr.replace(/\&\;#/g, '<sup>&#');</code>
Additional Considerations
The above is the detailed content of How to Encode HTML Entities in JavaScript: A Practical Guide. For more information, please follow other related articles on the PHP Chinese website!