长虫山小木屋

没有谁会为你踏雪而来 喜欢的风景要躬亲筚路

  博客园  :: 首页  :: 新随笔  :: 联系 ::  :: 管理
  115 随笔 :: 0 文章 :: 6 评论 :: 90329 阅读

两个方法:

1、利用用浏览器内部转换器实现html转义;

2、用正则表达式实现html转义;

 

复制代码
var HtmlUtil = {
        /*1.用浏览器内部转换器实现html编码(转义)*/
        htmlEncode:function (html){
            //1.首先动态创建一个容器标签元素,如DIV
            var temp = document.createElement ("div");
            //2.然后将要转换的字符串设置为这个元素的innerText或者textContent
            (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或者textContent,即得到经过HTML解码的字符串了。
            var output = temp.innerText || temp.textContent;
            temp = null;
            return output;
        },
        /*3.用正则表达式实现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.用正则表达式实现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.用正则表达式实现html编码(转义)(另一种写法)*/
        html2Escape:function(sHtml) {
             return sHtml.replace(/[<>&"]/g,function(c){return {'<':'<','>':'>','&':'&','"':'"'}[c];});
        },
        /*6.用正则表达式实现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];});
        }
    };
复制代码

 来源:https://www.cnblogs.com/willingtolove/p/11059325.html

posted on   长虫山小木屋  阅读(222)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示