Method 1:
Use a browser internal converter to implement conversion by dynamically creating a container label element, such as DIV, and setting the string to be converted to the innerText of this element (ie supported) | textContent (supported by Firefox). Then, the innerHTML of this element is returned to obtain the HTML-encoded string, which is displayed in turn. (In fact, conversion is not required during display, directly assign a value to the div to display it normally ).
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function HTMLEncode (html)
{
Var temp = document. createElement ("div ");
(Temp. textContent! = Null )? (Temp. textContent = html): (temp. innerText = html );
Var output = temp. innerHTML;
Temp = null;
Return output;
}
Function HTMLDecode (text)
{
Var temp = document. createElement ("div ");
Temp. innerHTML = text;
Var output = temp. innerText | temp. textContent;
Temp = null;
Return output;
}
Var html = "<br> dffdf <p> qqqqq </p> ";
Var encodeHTML = HTMLEncode (html );
Alert ("Method 1:" + encodeHTML );
Var decodeHTML = HTMLDecode (encodeHTML );
Alert ("Method 1:" + decodeHTML );
</Script>
Method 2:
Convert <> and space characters into html encoding by using a regular expression. Because this method is not built-in to the system, it is easy to see that some special labels are not replaced, and the efficiency is low.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function HTMLEncode2 (str)
{
Var s = "";
If (str. length = 0) return "";
S = str. replace (/&/g ,"&");
S = s. replace (/</g, "<");
S = s. replace (/>/g, "> ");
S = s. replace (// g ,"");
S = s. replace (/\ '/g ,"'");
S = s. replace (/\ "/g ,""");
Return s;
}
Function HTMLDecode2 (str)
{
Var s = "";
If (str. length = 0) return "";
S = str. replace (/&/g ,"&");
S = s. replace (/</g, "<");
S = s. replace (/>/g, "> ");
S = s. replace (// g ,"");
S = s. replace (/'/g ,"\'");
S = s. replace (/"/g ,"\"");
Return s;
}
Var html = "<br> ccccc <p> aaaaa </p> ";
Var encodeHTML = HTMLEncode2 (html );
Alert ("Method 2:" + encodeHTML );
Var decodeHTML = HTMLDecode2 ("Method 2:" + encodeHTML );
Alert (decodeHTML );
</Script>