This article illustrates the JavaScript alternative method for implementing HTMLEncode () and HtmlDecode () functions. Share to everyone for your reference, specific as follows:
The most common practice is the use of regular expression replacement method, the special character Furu < > &, etc. to replace, HTMLEncode when this replacement is relatively easy, but when the htmldecode is not necessarily useful, because the need to reverse the situation a lot, out of the common <>& Besides, there are dozens of character entities, such as AB Chinese or Chinese characters Unicode encoded decimal or 16 in the escape, it is difficult to enumerate all, replace the code is not only lengthy and inefficient, but also easily missing some characters.
The code is as follows:
function HTMLEncode (s) {
var div = document.createelement (' div ');
Div.appendchild (document.createTextNode (s));
return div.innerhtml;
}
function HtmlDecode (s) {
var div = document.createelement (' div ');
div.innerhtml = s;
return Div.innertext | | div.textcontent;
}
Quite concise!
The coding principle is to create textnode nodes, attach them to the container, and then take 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 () {
//<p> & </p>
alert (HTMLEncode (' <p> & </ P> '));
<p> &©abc Chinese </p>
alert (HtmlDecode (' <p> &©abc Chinese Language </p> '));
The effect is good.
HtmlDecode is required for an incoming parameter, and the expected result may not be obtained if the entry is not a legitimate encode result.
I was in Google search, in Cnblogs found a and I think the same way, the original has been someone else like this =| | =, but his htmldecode code has errors.
More readers interested in JavaScript-related content can view the site topics: "JavaScript coding Operation Tips Summary", "JavaScript switching effects and techniques summary", "JavaScript Search Algorithm Skills summary", " JavaScript animation effects and tips Summary, "JavaScript Error and debugging skills Summary", "JavaScript data structure and algorithm skills summary", "JavaScript traversal algorithm and Skills summary" and "JavaScript Mathematical operation Usage Summary"
I hope this article will help you with JavaScript programming.