1. Escaping HTML Characters with a Text Node
A string can be treated as plain text first, then read back through an element’s innerHTML.
Code:
let textNode = document.createTextNode('<span>by zhangxinxu</span>');
let div = document.createElement('div');
div.append(textNode);
console.log(div.innerHTML);
Result:
Text node value
<span>by zhangxinxu</span>
div.innerHTML
Console
2. Unescaping HTML Characters with DOMParser
DOMParser asks the browser to parse escaped HTML as a document, then reads the text content back.
Code:
let str = '<span>by zhangxinxu</span>';
let doc = new DOMParser().parseFromString(str, 'text/html');
console.log(doc.documentElement.textContent);
Result:
Escaped input
<span>by zhangxinxu</span>
documentElement.textContent
Console
3. Unescaping HTML Characters with a Textarea
A textarea also decodes entities when assigned through innerHTML, which makes its child text node useful for old-browser-style decoding.
Code:
let textarea = document.createElement('textarea');
textarea.innerHTML = '<span>by zhangxinxu</span>';
console.log(textarea.childNodes[0].nodeValue);
Result:
textarea.innerHTML
<span>by zhangxinxu</span>
childNodes[0].nodeValue
Console
4. Browser-Free Fallback with String Replacement
Outside a browser context, the DOM helpers are unavailable, so a direct string replacement fallback is still useful.
Code:
/**
* Method for escaping HTML tags
* @param {String} str The HTML string to escape
* @return {String} The escaped string
*/
var funEncodeHTML = function (str) {
if (typeof str == 'string') {
return str.replace(/<|&|>/g, function (matches) {
return ({
'<': '<',
'>': '>',
'&': '&'
})[matches];
});
}
return '';
};
/**
* Method for unescaping HTML tags
* @param {String} str The string to unescape
* @return {String} The unescaped string
*/
var funDecodeHTML = function (str) {
if (typeof str == 'string') {
return str.replace(/<|>|&/g, function (matches) {
return ({
'<': '<',
'>': '>',
'&': '&'
})[matches];
});
}
return '';
};
let encoded = funEncodeHTML('<span>by zhangxinxu</span>');
console.log(encoded);
console.log(funDecodeHTML(encoded));
Result:
funEncodeHTML result
funDecodeHTML result
Console