Home > Web Front-end > JS Tutorial > How Can I Reliably Decode HTML Special Entities in JavaScript?

How Can I Reliably Decode HTML Special Entities in JavaScript?

Barbara Streisand
Release: 2024-12-04 11:06:12
Original
595 people have browsed it

How Can I Reliably Decode HTML Special Entities in JavaScript?

Decoding HTML Special Entities with Confidence

When parsing JSON responses, you may encounter strings with encoded special HTML entities like "'" for apostrophes. While jQuery's 'decodeHtml' offers a simple solution, it feels inadequate. Let's explore a more robust approach.

The preferred method involves using a textarea element:

function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}
Copy after login

This technique effectively decodes HTML entities while preserving tags. To demonstrate:

Input:

Entity:&amp;nbsp;Bad attempt at XSS:<script>alert('new\nline?')</script><br>
Copy after login

Output:

Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>
Copy after login

The spaces, newlines, and tags within the script tags are accurately preserved. This approach ensures reliable decoding of HTML entities, making it the "right" solution for your task.

The above is the detailed content of How Can I Reliably Decode HTML Special 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