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";
I know I'm a bit late to the game, but I thought I might provide the following snippet as an example of how I decode HTML entities using jQuery:
Don't forget to fire-up your inspector/firebug to see the console results -- or simply replace console.log(...) w/alert(...)
That said, here's what my console via the Google Chrome inspector read:
You also asked how to encode them - you can use server-side functionality, or you can create your own object to do the mapping, e.g. clj: A function to convert extended character ?
This is my favourite way of decoding HTML characters. The advantage of using this code is that tags are also preserved.
Example: http://jsfiddle.net/k65s3/
Input:
Output:
Injecting untrusted HTML into the page is dangerous as explained in How to decode HTML entities using jQuery?.
One alternative is to use a JavaScript-only implementation of PHP's html_entity_decode (from http://phpjs.org/functions/html_entity_decode:424). The example would then be something like:
I recommend against using the jQuery code that was accepted as the answer. While it does not insert the string to decode into the page, it does cause things such as scripts and HTML elements to get created. This is way more code than we need. Instead, I suggest using a safer, more optimized function.
http://jsfiddle.net/LYteC/4/
To use this function, just call
decodeEntities("&")
and it will use the same underlying techniques as the jQuery version will—but without jQuery's overhead, and after sanitizing the HTML tags in the input. See Mike Samuel's comment on the accepted answer for how to filter out HTML tags.This function can be easily used as a jQuery plugin by adding the following line in your project.
Here's a quick method that doesn't require creating a div, and decodes the "most common" HTML escaped chars: