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

How to Encode HTML Entities in JavaScript: A Practical Guide

Susan Sarandon
Release: 2024-10-29 07:07:30
Original
643 people have browsed it

How to Encode HTML Entities in JavaScript: A Practical Guide

Encoding HTML Entities in JavaScript

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<>\&amp;]/g, function(i) {
   return '&amp;#'+i.charCodeAt(0)+';';
});</code>
Copy after login

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

// Then, wrap the encoded entity in a `<sup>` tag:

const supEncodedStr = encodedStr.replace(/\&amp\;#/g, '<sup>&amp;#');</code>
Copy after login

Additional Considerations

  • Ensure your website uses UTF8 character encoding to support these special characters.
  • Test the conversion in different browsers to account for font and configuration variations.

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!

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