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
Barbara StreisandOriginal
2024-12-04 11:06:12637browse

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;
}

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>

Output:

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

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!

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