Home > Web Front-end > JS Tutorial > body text

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

Susan Sarandon
Release: 2024-10-31 07:08:30
Original
676 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!