方法一:
用的瀏覽器內部轉換器實現轉換,方法是動態建立一個容器標籤元素,如DIV,將要轉換的字串設定為這個元素的innerText(ie支援)||textContent(Firefox支援),然後返回這個元素的innerHTML,即得到經過HTML編碼轉換的字串,顯示的時候反過來就可以了(實際上顯示的時候不用通過轉換,直接賦值在div就可以正常顯示的)。
複製代碼 代碼如下:<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("方式一:" + encodeHTML);
var decodeHTML = HTMLDecode(encodeHTML);
alert("方式一:" + decodeHTML);
</script>
方法二:
通過把Regex把<>和空格符轉換成html編碼,由於這種方式不是系統內建的所以很容易出現有些特殊標籤沒有替換的情況,而且效率低下 複製代碼 代碼如下:<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("方式二:" + encodeHTML);
var decodeHTML = HTMLDecode2("方式二:" + encodeHTML);
alert(decodeHTML);
</script>