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
Release: 2024-11-30 19:51:19
Original
353 people have browsed it

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

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

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

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!

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