方法一: 用的浏览器内部转换器实现转换,方法是动态创建一个容器标签元素,如DIV,将要转换的字符串设置为这个元素的innerText(ie支持)||textContent(火狐支持),然后返回这个元素的innerHTML,即得到经过HTML编码转换的字符串,显示的时候反过来就可以了(实际上显示的时候不用通过转换,直接赋值在div就可以正常显示的)。 复制代码 代码如下: <BR>function HTMLEncode(html) <BR>{ <BR>var temp = document.createElement ("div"); <BR>(temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html); <BR>var output = temp.innerHTML; <BR>temp = null; <BR>return output; <BR>} <BR>function HTMLDecode(text) <BR>{ <BR>var temp = document.createElement("div"); <BR>temp.innerHTML = text; <BR>var output = temp.innerText || temp.textContent; <BR>temp = null; <BR>return output; <BR>} <BR>var html = "<br>dffdf<p>qqqqq"; <BR>var encodeHTML = HTMLEncode(html); <BR>alert("方式一:" + encodeHTML); <BR>var decodeHTML = HTMLDecode(encodeHTML); <BR>alert("方式一:" + decodeHTML); <BR> 方法二: 通过把正则表达式把和空格符转换成html编码,由于这种方式不是系统内置的所以很容易出现有些特殊标签没有替换的情况,而且效率低下 复制代码 代码如下: <BR>function HTMLEncode2(str) <BR>{ <BR>var s = ""; <BR>if(str.length == 0) return ""; <BR>s = str.replace(/&/g,"&"); <BR>s = s.replace(/,"<"); <BR>s = s.replace(/>/g,">"); <BR>s = s.replace(/ /g," "); <BR>s = s.replace(/\'/g,"'"); <BR>s = s.replace(/\"/g,"""); <BR>return s; <BR>} <BR>function HTMLDecode2(str) <BR>{ <BR>var s = ""; <BR>if(str.length == 0) return ""; <BR>s = str.replace(/&/g,"&"); <BR>s = s.replace(/,"<"); <BR>s = s.replace(/>/g,">"); <BR>s = s.replace(/ /g," "); <BR>s = s.replace(/'/g,"\'"); <BR>s = s.replace(/"/g,"\""); <BR>return s; <BR>} <BR>var html = "<br>ccccc<p>aaaaa"; <BR>var encodeHTML = HTMLEncode2(html); <BR>alert("方式二:" + encodeHTML); <BR>var decodeHTML = HTMLDecode2("方式二:" + encodeHTML); <BR>alert(decodeHTML); <BR>