1. 程式人生 > >javascript對HTML字元編碼及解碼

javascript對HTML字元編碼及解碼

<script>
var HtmlUtil = {
        /*1.用瀏覽器內部轉換器實現html轉碼*/
        htmlEncode:function (html){
            //1.首先動態建立一個容器標籤元素,如DIV
            var temp = document.createElement ("div");
            //2.然後將要轉換的字串設定為這個元素的innerText(ie支援)或者textContent(火狐,google支援)
            (temp.textContent != undefined ) ? (temp.textContent = html) : (temp.innerText = html);
            //3.最後返回這個元素的innerHTML,即得到經過HTML編碼轉換的字串了
            var output = temp.innerHTML;
            temp = null;
            return output;
        },
        /*2.用瀏覽器內部轉換器實現html解碼*/
        htmlDecode:function (text){
            //1.首先動態建立一個容器標籤元素,如DIV
            var temp = document.createElement("div");
            //2.然後將要轉換的字串設定為這個元素的innerHTML(ie,火狐,google都支援)
            temp.innerHTML = text;
            //3.最後返回這個元素的innerText(ie支援)或者textContent(火狐,google支援),即得到經過HTML解碼的字串了。
            var output = temp.innerText || temp.textContent;
            temp = null;
            return output;
        },
        /*3.用正則表示式實現html轉碼*/
        htmlEncodeByRegExp:function (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; 
       },
       /*4.用正則表示式實現html解碼*/
       htmlDecodeByRegExp:function (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; 
       }
    };
</script>

呼叫方法:HtmlUtil.htmlDecodeByRegExp("&amp;");