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

How to Safely Decode HTML Entities in JavaScript?

Linda Hamilton
Release: 2024-12-23 16:10:18
Original
432 people have browsed it

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;
}
Copy after login

Example usage:

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

console.log(htmlDecode("<img src='dummy' onerror='alert(/xss/)'>")); // ""
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template