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.