Unescape HTML Characters with JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to unescape HTML characters using JavaScript. HTML escaping is a common technique used to encode special characters in HTML to prevent cross-site scripting attacks. However, sometimes we need to convert the escaped characters back to their original form. We will learn how to do this by creating a function that unescapes the most common HTML characters.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28677{{"`Unescape HTML Characters with JavaScript`"}} javascript/data_types -.-> lab-28677{{"`Unescape HTML Characters with JavaScript`"}} javascript/arith_ops -.-> lab-28677{{"`Unescape HTML Characters with JavaScript`"}} javascript/comp_ops -.-> lab-28677{{"`Unescape HTML Characters with JavaScript`"}} end

Unescape HTML

This function unescapes escaped HTML characters. To use it, follow these steps:

  1. Open the Terminal/SSH.
  2. Type node.
  3. Copy and paste the following code:
const unescapeHTML = (str) =>
  str.replace(
    /&|<|>|'|"/g,
    (tag) =>
      ({
        "&": "&",
        "&lt;": "<",
        "&gt;": ">",
        "&#39;": "'",
        "&quot;": '"'
      })[tag] || tag
  );
  1. Call the unescapeHTML function and pass it a string with escaped characters.
  2. The function will return the unescaped string.

Example usage:

unescapeHTML("&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;");
// '<a href="#">Me & you</a>'

Summary

Congratulations! You have completed the Unescape HTML lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like