Home >Web Front-end >JS Tutorial >How to Safely Decode HTML Entities in JavaScript?

How to Safely Decode HTML Entities in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-23 16:10:18460browse

How to Safely Decode HTML Entities in JavaScript?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn