An example of how to implement the htmlencode () and htmldecode () functions in javascript is described in this document. We will share this with you for your reference. The details are as follows:
The most common practice is to replace special characters such as <> & with regular expressions. It is easier to replace special characters such as <> & with htmlencode, however, it may not be easy to use when htmldecode is sent, because there are many situations that need to be reversed. There are also dozens of character entities such as <>, in addition, it is difficult to list all escape characters in the Unicode-encoded decimal or hexadecimal notation such as AB Chinese or Chinese. Replacing them one by one is not only lengthy and inefficient, but also easy to miss some characters.
The Code is as follows:
function htmlencode(s){ var p = document.createElement('p'); p.appendChild(document.createTextNode(s)); return p.innerHTML;}function htmldecode(s){ var p = document.createElement('p'); p.innerHTML = s; return p.innerText || p.textContent;}
Very concise!
The encoding principle is to create a TextNode node, attach it to the container, and then retrieve the innerHTML of the container.
The decoding principle is to assign the string to the innerHTML of the container, and then take innerText or textContent.
Test:
// Test document. onclick = function (){//&
Alert (htmlencode ('&
'));//& ABC Chinese
Alert (htmldecode ('& ABC Chinese
'));}
Good results.
Htmldecode requires an input parameter. If the input parameter is not the result of a valid encode, the expected result may not be obtained.
I searched in google and found an article in cnblogs that had the same idea as me. Someone else thought like this ||=, but his htmldecode code has an error.