How to Successfully Decode HTML Entities in Javascript
Javascript often interacts with external sources like XML-RPC backends. These backends may return strings containing HTML entities like . When attempting to incorporate these strings into HTML using Javascript, they might render literally or appear as an unescaped HTML entity.
To effectively unescape these HTML entities, utilizing techniques from external sources may prove unsuccessful. Instead, leverage the DOMParser method supported in modern browsers. Here's how it's done:
function htmlDecode(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }
Example usage:
console.log(htmlDecode("<img src='myimage.jpg'>")); // "<img src='myimage.jpg'>" console.log(htmlDecode("<img src='dummy' onerror='alert(/xss/)'>")); // ""
This method successfully decodes HTML entities while preventing the execution of malicious code.
The above is the detailed content of How to Safely Decode HTML Entities in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!