Home >Web Front-end >JS Tutorial >How to Effectively Decode HTML Entities in JSON Data?

How to Effectively Decode HTML Entities in JSON Data?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 19:51:19427browse

How to Effectively Decode HTML Entities in JSON Data?

Decoding Strings with Special HTML Entities

When receiving JSON data containing encoded HTML entities, decoding them properly is crucial. A simple jQuery approach to do this is:

function decodeHtml(html) {
    return $('<div>').html(html).text();
}

While effective, this technique is considered a "hack." A more robust and preferred method is to utilize the DOMParser as follows:

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

This method not only decodes entities but also preserves HTML tags, making it a more comprehensive and widely accepted approach.

An example showcasing the decoding process:

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 above is the detailed content of How to Effectively Decode HTML Entities in JSON Data?. 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