1.用瀏覽器內(nèi)部轉換器實現(xiàn)html編碼(轉義)
? ? ? ? htmlEncode:function (html){
? ? ? ? ? ? //1.首先動態(tài)創(chuàng)建一個容器標簽元素,如DIV
? ? ? ? ? ? var temp = document.createElement ("div");
? ? ? ? ? ? //2.然后將要轉換的字符串設置為這個元素的innerText或者textContent
? ? ? ? ? ? (temp.textContent != undefined ) ? (temp.textContent = html) : (temp.innerText = html);
? ? ? ? ? ? //3.最后返回這個元素的innerHTML,即得到經(jīng)過HTML編碼轉換的字符串了
? ? ? ? ? ? var output = temp.innerHTML;
? ? ? ? ? ? temp = null;
? ? ? ? ? ? return output;
? ? ? ? },
2.用瀏覽器內(nèi)部轉換器實現(xiàn)html解碼(反轉義)
? ? ? ? htmlDecode:function (text){
? ? ? ? ? ? //1.首先動態(tài)創(chuàng)建一個容器標簽元素,如DIV
? ? ? ? ? ? var temp = document.createElement("div");
? ? ? ? ? ? //2.然后將要轉換的字符串設置為這個元素的innerHTML(ie爱致,火狐渣淳,google都支持)
? ? ? ? ? ? temp.innerHTML = text;
? ? ? ? ? ? //3.最后返回這個元素的innerText或者textContent,即得到經(jīng)過HTML解碼的字符串了指孤。
? ? ? ? ? ? var output = temp.innerText || temp.textContent;
? ? ? ? ? ? temp = null;
? ? ? ? ? ? return output;
? ? ? ? },
3.用正則表達式實現(xiàn)html編碼(轉義)
? ? ? ? htmlEncodeByRegExp:function (str){
? ? ? ? ? ? var temp = "";
? ? ? ? ? ? if(str.length == 0) return "";
? ? ? ? ? ? temp = str.replace(/&/g,"&");
? ? ? ? ? ? temp = temp.replace(/</g,"<");
? ? ? ? ? ? temp = temp.replace(/>/g,">");
? ? ? ? ? ? temp = temp.replace(/\s/g,"?");
? ? ? ? ? ? temp = temp.replace(/\'/g,"'");
? ? ? ? ? ? temp = temp.replace(/\"/g,""");
? ? ? ? ? ? return temp;
? ? ? ? },
4.用正則表達式實現(xiàn)html解碼(反轉義)
? ? ? ? htmlDecodeByRegExp:function (str){
? ? ? ? ? ? var temp = "";
? ? ? ? ? ? if(str.length == 0) return "";
? ? ? ? ? ? temp = str.replace(/&/g,"&");
? ? ? ? ? ? temp = temp.replace(/</g,"<");
? ? ? ? ? ? temp = temp.replace(/>/g,">");
? ? ? ? ? ? temp = temp.replace(/?/g," ");
? ? ? ? ? ? temp = temp.replace(/'/g,"\'");
? ? ? ? ? ? temp = temp.replace(/"/g,"\"");
? ? ? ? ? ? return temp;
? ? ? ? },
5.用正則表達式實現(xiàn)html編碼(轉義)(另一種寫法)
? ? ? ? html2Escape:function(sHtml) {
? ? ? ? ? ? return sHtml.replace(/[<>&"]/g,function(c){return {'<':'<','>':'>','&':'&','"':'"'}[c];});
? ? ? ? },
6.用正則表達式實現(xiàn)html解碼(反轉義)(另一種寫法)
? ? ? ? escape2Html:function (str) {
? ? ? ? ? ? var arrEntities={'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'};
? ? ? ? ? ? return str.replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){return arrEntities[t];});
? ? ? ? }