Method One:
Use the browser internal converter to implement the conversion, the main point is to dynamically create a container tag elements, such as Div, the string to be converted is set to this element 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, when the display does not eliminate the conversion, directly assigned to the Div can be normal display).
<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 one:" +encodehtml); var decodehtml = HtmlDecode (encodehtml); Alert ("Method one:" +decodehtml); </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
The second method: regular replacement
By converting the regular expression to HTML encoding <> and spaces, because this method is not built into the system, it is very easy to have some special tags that are not replaced and inefficient
<textarea id="runcode20644"><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>cccccaaaaa"; var encodehtml = HTMLEncode2 (HTML); Alert ("Method two:" +encodehtml); var decodehtml = HTMLDecode2 (encodehtml); Alert ("Method two:" +decodehtml); </script></textarea>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
We can run the test first, I also found that the first method is more useful ah, really good, we must remember.
In addition, some editors use some HTMLEncode functions, then you need to add, but the need to remind that the code must be tested AH, cloud Habitat Community jb51.net Webmaster Release This message when the test is really troublesome Ah, modified a number of times
Copy Code code as follows:
function HTMLEncode (text) {
Text = Text.replace (/&/g, "&");
Text = text.replace (/"/g," "");
Text = Text.replace (/</g, "<");
Text = Text.replace (/>/g, ">");
Text = Text.replace (/\/g, "");
Text = Text.replace (/\n/g, "<br>");
Text = Text.replace (/\t/g, "");
return text;
}