A complete example of JavaScript htmlencode and htmldecode compatible with IE and ff. Because this is often used in online editors and Ajax, encapsulated functions can be called directly. I hope it will be helpful to you.
<HTML>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = GBK"/>
<Title> htmlecode </title>
</Head>
<Body>
Method 1: <br>
<Br>
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, you can display it in turn. (In actual display, you do not need to convert it. You can directly assign a value to the DIV to display it normally ).
<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: <br>
<Br>
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.
<SCRIPT type = "text/JavaScript">
Function htmlencode2 (STR)
{
VaR S = "";
If (Str. Length = 0) Return "";
S = Str. Replace (/&/g, "& amp ;");
S = S. Replace (/</g, "& lt ;");
S = S. Replace (/>/g, "& gt ;");
S = S. Replace (// G, "& nbsp ;");
S = S. Replace (/\ '/g, "& #39 ;");
S = S. Replace (/\ "/g," & quot ;");
Return S;
}
Function htmldecode2 (STR)
{
VaR S = "";
If (Str. Length = 0) Return "";
S = Str. Replace (/& amp;/g ,"&");
S = S. Replace (/& lt;/g, "<");
S = S. Replace (/& gt;/g, "> ");
S = S. Replace (/& nbsp;/g ,"");
S = S. Replace (/& #39;/g ,"\'");
S = S. Replace (/& quot;/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>
</Body>
</Html>