Sometimes we may have to use js to process HTML entities. For example& Gt;This content is converted>Symbol, or the opposite operation. If you encounter such a requirement unfortunately, the following content may be helpful.
The implementation of unescapehtmlentities is very simple. Create a node element, write the string to the innerhtml attribute of the element, and return the text content of the element. Passing parameters when calling the following functions'& Gt ;', The result will be'>'
function unescapeHtmlEntities(str) {var tempEle = document.createElement("div");tempEle.innerHTML = str;var result = tempEle.childNodes[0].nodeValue;return result;}
The process of escapehtmlentities is the opposite. When an element is created, a text node is inserted, and the innerhtml of the element is read, the entity of the character is obtained. Passing parameters when calling the following functions'>', The result will be'& Gt ;'
function escapeHtmlEntities(str) {var tempEle = document.createElement("div");tempText = document.createTextNode(str);tempEle.appendChild(tempText);var result = tempEle.innerHTML;return result;}alert(escapeHtmlEntities('>')); // result : >
If jquery is used, the two functions can be completed in one sentence:
function unescapeHtmlEntities(str) { return $('<div />').html(str).text();}
function escapeHtmlEntities(str){ return $('<div />').text(str).html();}
However, processing HTML entities is not recommended in the behavior layer.In fact, templates and backend languages can work better, such as htmlentities of PHP: