Categories
JavaScript Answers

How to unescape HTML entities in JavaScript?

Spread the love

To unescape HTML entities in JavaScript, we can use the DOMParser constructor.

For instance, we write

const htmlDecode = (input) => {
  const doc = new DOMParser().parseFromString(input, "text/html");
  return doc.documentElement.textContent;
};

console.log(htmlDecode("<img src='myimage.jpg'>"));

to define the htmlDecode function.

In it, we get the input string and parse it into a DOM object.

We create a DOMParser object and call it parseFromString method with the input and MIME type string to parse the input into a DOM object.

Then we get the textContent from the DOM object to get the HTML string unescaped.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *