How do I use jQuery to decode HTML entities in a string?
Without any jQuery:
function decodeEntities(encodedString) {
var textArea = document.createElement('textarea');
textArea.innerHTML = encodedString;
return textArea.value;
}
console.log(decodeEntities('1 & 2')); // '1 & 2'
This works similarly to the accepted answer, but is safe to use with untrusted user input.
As noted by Mike Samuel, doing this with a However, this attack is not possible against a Warning: Doing this using jQuery's .html() and .val() methods instead of using .innerHTML and * Thanks to Eru Penkman for catching this vulnerability. with untrusted user input is an XSS vulnerability, even if the function decodeEntities(encodedString) {
var div = document.createElement('div');
div.innerHTML = encodedString;
return div.textContent;
}
// Shows an alert
decodeEntities('')
because there are no HTML elements that are permitted content of a function decodeEntities(encodedString) {
var textArea = document.createElement('textarea');
textArea.innerHTML = encodedString;
return textArea.value;
}
// Safe, and returns the correct answer
console.log(decodeEntities(''))
.value is also insecure* for some versions of jQuery, even when using a textarea. This is because older versions of jQuery would deliberately and explicitly evaluate scripts contained in the string passed to .html(). Hence code like this shows an alert in jQuery 1.8://