Unescape HTML entities in Javascript? Unescape HTML entities in Javascript? javascript javascript

Unescape HTML entities in Javascript?


Most answers given here have a huge disadvantage: if the string you are trying to convert isn't trusted then you will end up with a Cross-Site Scripting (XSS) vulnerability. For the function in the accepted answer, consider the following:

htmlDecode("<img src='dummy' onerror='alert(/xss/)'>");

The string here contains an unescaped HTML tag, so instead of decoding anything the htmlDecode function will actually run JavaScript code specified inside the string.

This can be avoided by using DOMParser which is supported in all modern browsers:

function htmlDecode(input) {  var doc = new DOMParser().parseFromString(input, "text/html");  return doc.documentElement.textContent;}console.log(  htmlDecode("<img src='myimage.jpg'>")  )    // "<img src='myimage.jpg'>"console.log(  htmlDecode("<img src='dummy' onerror='alert(/xss/)'>")  )  // ""