4種方法實現Html轉碼
阿新 • • 發佈:2019-02-11
extc 設置 rip efi lencod undefined tput tee class
<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; console.log(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; console.log(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, """); s = s.replace(/¥/g, "¥"); //return s; console.log(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, ‘"‘); s = s.replace(/¥/g, "¥"); // return s; console.log(s); } }; HtmlUtil.htmlEncode(‘<div>¥</div>‘); HtmlUtil.htmlDecode(‘¥‘); HtmlUtil.htmlEncodeByRegExp(‘<div>¥</div>‘); HtmlUtil.htmlDecodeByRegExp(‘¥‘) </script>
結果如下:
4種方法實現Html轉碼