Easy Solution to Encode HTML Entities in JavaScript

  1. Use String.prototype.toHtmlEntities() to Encode String to HTML Entities
  2. Use String.fromHtmlEntities() to Encode String From HTML Entities
  3. Use the unescapeHTML() Function to Encode HTML Entities in JavaScript
Easy Solution to Encode HTML Entities in JavaScript

This article explains the best solutions to Encode HTML entities in JavaScript. Example code below translates any string to HTML entities and back on string prototype.

Use String.prototype.toHtmlEntities() to Encode String to HTML Entities

In the following JavaScript code,

  • String.prototype.toHtmlEntities = function() returns a string containing HTML entities with the help of .replace() method.
  • .replace() finds the given string’s value and changes it with the new desired/specified value.
  • .prototype is an object in JavaScript. It associates with functions and objects by default.
  • String.charCodeAt() returns the Unicode of the character that has described index in a string.
/**
 * Conversion of string to HTML entities
 */
String.prototype.toHtmlEntities = function() {
  return this.replace(/./gm, function(s) {
    // return "&#" + s.charCodeAt(0) + ";";
    return (s.match(/[a-z0-9\s]+/i)) ? s : '&#' + s.charCodeAt(0) + ';';
  });
};

Use String.fromHtmlEntities() to Encode String From HTML Entities

In the following JavaScript statements, we have created:

  • String.fromHtmlEntities = function(string) that receives any string which contains HTML entities.
  • Here in example, the given string value in .replace() is /&#\d+;/gm that is replaced with a function(s) which returns a string String.fromCharCode.
  • String.fromCharCode is a method that returns a string generated by a sequence.
/**
 * Creation of string from HTML entities
 */
String.fromHtmlEntities = function(string) {
  return (string + '').replace(/&#\d+;/gm, function(s) {
    return String.fromCharCode(s.match(/\d+/gm)[0]);
  })
};

After that, use the function as below.

  • Here is a variable var str that is initialized with a string containing special characters (†®¥¨©˙∫ø…ˆƒ∆...).
  • A function .toHtmlEntities is called with this special character string var str.
  • console.log is a default function of JavaScript that displays values in the log box.
var str = "Dummy Test´†®¥¨©˙∫ø…ˆƒ∆÷∑™ƒ∆æø𣨠ƒ™en tést".toHtmlEntities();
console.log("Entities:", str);
console.log("String:", String.fromHtmlEntities(str));

The output from the console is as follows.

"Entities:"
"Test´†®¥¨©˙∫ø…ˆƒ∆÷∑™ƒ∆æø𣨠ƒ™en tést"
"String:"
"Dummy Test´†®¥¨©˙∫ø…ˆƒ∆÷∑™ƒ∆æø𣨠ƒ™en tést"

Use the unescapeHTML() Function to Encode HTML Entities in JavaScript

You can check these functions on JavaScript compilers online or offline. It helps you to display the string without the browser reading its HTML. This can be done in another way. You can create an object of HTML entities.

  • A variable var htmlEntities contains object of special characters and symbols.
  • An unescapeHTML(str) function receives string and return values with the help of .replace() conditions.
var htmlEntities = {
  nbsp: ' ',
  cent: '¢',
  pound: '£',
  yen: '¥',
  euro: '€',
  copy: '©',
  reg: '®',
  lt: '<',
  gt: '>',
  quot: '"',
  amp: '&',
  apos: '\''
};

function unescapeHTML(str) {
  return str.replace(/\&([^;]+);/g, function(entity, entityCode) {
    var match;

    if (entityCode in htmlEntities) {
      return htmlEntities[entityCode];
      /*eslint no-cond-assign: 0*/
    } else if (match = entityCode.match(/^#x([\da-fA-F]+)$/)) {
      return String.fromCharCode(parseInt(match[1], 16));
      /*eslint no-cond-assign: 0*/
    } else if (match = entityCode.match(/^#(\d+)$/)) {
      return String.fromCharCode(~~match[1]);
    } else {
      return entity;
    }
  });
};

There isn’t any native version of HTML entities in JavaScript. If you just need basics to so that the browser won’t interpret as HTML. The PHP.js project], which is a task to port over each PHP’s local capacities to JavaScript, contains a model also. Along these lines, I’ve kept it straightforward and utilized the underneath:

function EntitiesHtml(string) {
  return String(string)
      .replace(/&/g, '&amp;')
      .replace(/>/g, '&gt;')
      .replace(/</g, '&lt;')
      .replace(/"/g, '&quot;');
}