How to unescape HTML entities in JavaScript?

Spread the love

Sometimes, we want to unescape HTML entities in JavaScript.

In this article, we’ll look at how to unescape HTML entities in JavaScript.

How to unescape HTML entities in JavaScript?

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

For instance, we write

const encodedStr = "hello & world";

const parser = new DOMParser();
const dom = parser.parseFromString(
  `<!doctype html><body>${encodedStr}</body>`,
  "text/html"
);
const decodedString = dom.body.textContent;
console.log(decodedString);

to call parser.parseFromString with the HTML we want to parse and the MIME type of the string being parsed.

Then we get the decoded content from dom.body.textContent.

Conclusion

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

Leave a Reply

Your email address will not be published.