This question already has an answer here:
- Unescape HTML entities in Javascript? 10 answers
How do I encode and decode HTML entities using JavaScript or JQuery?
var varTitle = "Chris' corner";
I want it to be:
var varTitle = "Chris' corner";
Inspired by Robert K's solution, strips html tags and prevents executing scripts and eventhandlers like:
<img src=fake onerror="prompt(1)">
Tested on latest Chrome, FF, IE (should work from IE9, but haven't tested).Simply call:
A more functional approach to @William Lahti's answer:
Like Robert K said, don't use jQuery.html().text() to decode html entities as it's unsafe because user input should never have access to the DOM. Read about XSS for why this is unsafe.
Instead try the Underscore.js utility-belt library which comes with escape and unescape methods:
_.escape(string)
Escapes a string for insertion into HTML, replacing
&
,<
,>
,"
,`
, and'
characters._.unescape(string)
The opposite of escape, replaces
&
,<
,>
,"
,`
and'
with their unescaped counterparts.To support decoding more characters, just copy the Underscore unescape method and add more characters to the map.
To do it in pure javascript without jquery or predefining everything you can cycle the encoded html string through an elements innerHTML and innerText(/textContent) properties for every decode step that is required:
jQuery provides a way to encode and decode html entities.
If you use a "<div/>" tag, it will strip out all the html.
If you use a "<textarea/>" tag, it will preserve the html tags.
Here is a full version
Usage