Home  >  Article  >  Web Front-end  >  How to Encode HTML Entities in JavaScript for Consistent User-Generated Content Display?

How to Encode HTML Entities in JavaScript for Consistent User-Generated Content Display?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 07:08:30678browse

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<>\&amp;]/g, function(i) {
   return '&amp;#'+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:

  1. Selects all elements with the ® symbol.
  2. Creates a sup element and adds it before the selected element.
  3. Appends the encoded HTML entity to the sup element.

Additional Considerations

  • Use UTF8 character encoding and database storage to ensure proper display.
  • Browser font configurations may still affect the appearance of certain characters.

Documentation

  • String.charCodeAt: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt
  • HTML Character Entities: http://www.chucke.com/entities.html

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn