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:&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!