How to Encode HTML With JavaScript

Habdul Hazeez Feb 02, 2024
  1. Encode HTML With String Replacement in JavaScript
  2. Encode HTML With the charCodeAt Function in JavaScript
  3. Encode HTML With createTextNode in JavaScript
  4. Encode HTML With He.js in JavaScript
How to Encode HTML With JavaScript

This article will introduce how to encode an HTML string in JavaScript. We’ll use four different methods, which have string replacement in common.

The purpose of the string replacement is to replace potentially dangerous characters.

Encode HTML With String Replacement in JavaScript

HTML encoding with string placement uses the replace() method in String.prototype.replace().

The replace() method takes a pattern and a replacement as an argument and matches based on the pattern. Let’s have a look at an example to see how this works.

In our example code below, we define a function that will take an HTML string as an argument. This function will return the encoded HTML.

function htmlEncode(string) {
  return string.replace(/&/g, '&')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/'/g, '&#39;')
      .replace(/"/g, '&#34;')
      .replace(/\//, '&#x2F;');
}

console.log(htmlEncode('<h1>Hello <span class=\'cool\'>world</span> </h1>'));

Output:

"&lt;h1&gt;Hello &lt;span class=&#39;cool&#39;&gt;world&lt;&#x2F;span&gt; &lt;/h1&gt;"

Encode HTML With the charCodeAt Function in JavaScript

The charCodeAt method returns an integer representing the UTF-16 code unit at an index. This makes it perfect for encoding some characters in your HTML.

We present an example code below where we’ve defined a function that takes a string as an argument.

We set up an array that acts as a buffer in the function definition. So, we loop through the array with a typical for loop.

During the loop, we use the unshift method to add some characters to the beginning of the array. These characters combine with &#, the integer returned by charCodeAt, and a semicolon.

We join them with the join function during the loop and when the function returns.

function encodeWithCharCode(string) {
  let buffer = [];

  for (let i = string.length - 1; i >= 0; i--) {
    buffer.unshift(['&#', string[i].charCodeAt(), ';'].join(''));
  }

  return buffer.join('');
}

console.log(encodeWithCharCode('<h1>Hello world</h1>'));

Output:

"&#60;&#104;&#49;&#62;&#72;&#101;&#108;&#108;&#111;&#32;&#119;&#111;&#114;&#108;&#100;&#60;&#47;&#104;&#49;&#62;"

Encode HTML With createTextNode in JavaScript

You can use the createTextNode method to encode a given HTML. The method accepts a string as an argument that it encodes behind the scenes.

Afterward, you can grab this encoded data. You can do all this with procedural programming or a function.

The function will accept an HTML string as an argument. Afterward, it creates an element with createElement and a text node with createTextNode.

In the end, the function appends this text node as the child of the created element and returns it via innerHTML. All along, createTextNode encodes the created text.

function encodeWithTextNode(htmlstring) {
  let textarea = document.createElement('textarea');
  let text = document.createTextNode(htmlstring);
  textarea.appendChild(text);
  return textarea.innerHTML;
}

console.log(
    encodeWithTextNode('<h1>Hello <span class=\'cool\'>world</span> </h1>'));

Output:

"&lt;h1&gt;Hello &lt;span class='cool'&gt;world&lt;/span&gt; &lt;/h1&gt;"

Encode HTML With He.js in JavaScript

He.js is an open-source entity encoder and decoder created by Mathias Bynens. To get started with the He.js library, visit the he.js GitHub repository.

Once you are there, select your preferred download option. You can embed He.js in your HTML code as an alternative option.

All you have to do is visit the cdnjs page for he.js and grab your preferred CDN link.

The next code block shows how to encode an HTML string with he.js.

<body>
	<script
		src="https://cdnjs.cloudflare.com/ajax/libs/he/1.2.0/he.min.js"
		integrity="sha512-PEsccDx9jqX6Dh4wZDCnWMaIO3gAaU0j46W//sSqQhUQxky6/eHZyeB3NrXD2xsyugAKd4KPiDANkcuoEa2JuA=="
		crossorigin="anonymous"
		referrerpolicy="no-referrer">
	</script>
	<script type="text/javascript">
		console.log(he.encode("<h1>Hello <span class='cool'>world</span> </h1>"));
	</script>
</body>

Output:

&#x3C;h1&#x3E;Hello &#x3C;span class=&#x27;cool&#x27;&#x3E;world&#x3C;/span&#x3E; &#x3C;/h1&#x3E;
Habdul Hazeez avatar Habdul Hazeez avatar

Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.

LinkedIn

Related Article - JavaScript HTML