Categories
JavaScript Answers

How to Unescape HTML Entities in JavaScript?

Spread the love

Sometimes, we may want to unescape strings with HTML entities in our web app.

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

Unescape HTML Entities with a Text Area

One way to unescape HTML entities is to put our escaped text in a text area.

This will unescape the text, so we can return the unescaped text afterward by getting the text from the text area.

For instance, we can write:

const htmlDecode = (input) => {
  const e = document.createElement('textarea');
  e.innerHTML = input;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

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

We have an htmlDecode function that takes an input string as a parameter.

In the function, we create the textarea element with the document.createElement .

Then we set the innerHTML of it to input .

Then we get the unescaped text by getting the childNodes[0].nodeValue property and return it.

Now when we pass in an escaped string, we’ll get the unescaped version back.

So “&lt;img src=’myimage.jpg’&gt;” becomes "<img src=’myimage.jpg’>" .

Use the DOMParser.prototype.parseFromString Method

Another way to unescape a string is to use the DOMParser.prototype.parseFromString method.

To use it, we pass in the escaped string, and the MIME type of the string to return.

For instance, we can use it by writing:

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

const result = htmlDecode("&lt;img src='myimage.jpg'&gt;");
console.log(result)

We create a new DOMParser instance.

Then we call parseFromString with the input string and the MIME type string of the string to convert to.

And then get the unescaped string with doc.documentElement.textContent and return it.

Therefore, result would be the same as the previous example.

Unescape HTML Entities with a Div

We can also create a div, set its innerHTML property to the escaped string.

Then we can get the unescaped string from the innerText property.

To do this, we write:

const htmlDecode = (input) => {
  const e = document.createElement('div');
  e.innerHTML = input;
  return e.innerText
}

const result = htmlDecode("&lt;img src='myimage.jpg'&gt;");
console.log(result)

We set e.innerHTML to input .

Then we return e.innerText to return the unescaped text.

And so we get the same result as the previous examples.

Conclusion

There are several ways we can use to unescape strings with HTML entities in JavaScript.

One reply on “How to Unescape HTML Entities in JavaScript?”

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.