Method One:
The browser internal converter implements the transformation by dynamically creating a container tag element, such as a Div, which is set to convert the string to the innertext (ie support) | | Textcontent (Firefox support), and then return the element of the innerHTML, that is, the HTML encoded conversion of the string, the display of the time can be reversed (in fact, the display without the conversion, directly assigned to the Div can be normal display).
Copy Code code 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 ("Mode one:" + encodehtml);
var decodehtml = HtmlDecode (encodehtml);
Alert ("Mode one:" + decodehtml);
</script>
Method Two:
By converting the regular expression to HTML encoding <> and spaces, because it is not built into the system, it is easy to have some special tags that are not replaced and inefficient
Copy Code code 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 ("mode two:" + encodehtml);
var decodehtml = HTMLDecode2 ("mode two:" + encodehtml);
alert (decodehtml);
</script>