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 ).
CopyCode The 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 code The 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>