js 用正则表达式实现 html 转码 / 解码

 

 

        var HtmlUtil = {
            /*1.用正则表达式实现html转码*/
            htmlEncode:function (str){  
                var s = "";
                if(str.length == 0) return "";
                s = str.replace(/&/g,"&");
                s = s.replace(/</g,"&lt;");
                s = s.replace(/>/g,"&gt;");
                s = s.replace(/ /g,"&nbsp;");
                s = s.replace(/\'/g,"&#39;");
                s = s.replace(/\"/g,"&quot;");
                return s;  
            },
            /*2.用正则表达式实现html解码*/
            htmlDecode:function (str){  
                var s = "";
                if(str.length == 0) return "";
                s = str.replace(/&amp;/g,"&");
                s = s.replace(/&lt;/g,"<");
                s = s.replace(/&gt;/g,">");
                s = s.replace(/&nbsp;/g," ");
                s = s.replace(/&#39;/g,"\'");
                s = s.replace(/&quot;/g,"\"");
                return s;  
            }
        };

 

 

调用:

var html = HtmlUtil.htmlDecode(str);

 

posted @ 2016-08-31 16:23  linyongqin  阅读(668)  评论(0编辑  收藏  举报