How to Escape and Unescape a HTML String in JavaScript

08/02/2021

Contents

In this article, you will learn how to escape and unescape a HTML string in JavaScript.

Escape and unescape a HTML string in JavaScript

HTML special characters such as <, >, &, and ” can cause display issues if they are not properly escaped. In JavaScript, you can escape and unescape HTML strings using built-in functions.

Using the escape() method

The escape() method is used to encode a string. Here is an example code snippet:

const htmlString = '<a href="#">Click Here</a>';
const escapedString = escape(htmlString);
console.log(escapedString); // Output: "%3Ca%20href%3D%22%23%22%3EClick%20Here%3C%2Fa%3E"

The escape() method replaces the special characters in the string with their ASCII codes.

Using the encodeURIComponent() method

The encodeURIComponent() method is used to encode a URI component. Here is an example code snippet:

const htmlString = '<a href="#">Click Here</a>';
const encodedString = encodeURIComponent(htmlString);
console.log(encodedString); // Output: "%3Ca%20href%3D%22%23%22%3EClick%20Here%3C%2Fa%3E"

The encodeURIComponent() method replaces all characters except the alphabets, digits, and special characters such as – _ . ! ~ * ‘ ( ) with their ASCII codes.

Using the replace() method to unescape HTML

The replace() method can be used to unescape HTML. Here is an example code snippet:

const htmlString = '<a href="#">Click Here</a>';
const unescapedString = htmlString.replace(/<|>|"|'|&/g, (match) => {
  switch(match) {
    case '<':
      return '<';
    case '>':
      return '>';
    case '"':
      return '"';
    case ''':
      return "'";
    case '&':
      return '&';
  }
});
console.log(unescapedString); // Output: "<a href="#">Click Here</a>"

The replace() method replaces the escaped characters in the string with their unescaped counterparts using a regular expression pattern and a switch statement.