首页 > 代码库 > JS及JQuery对Html内容编码,Html转义

JS及JQuery对Html内容编码,Html转义

/** JQuery Html Encoding、Decoding
* 原理是利用JQuery自带的html()和text()函数可以转义Html字符
* 虚拟一个Div通过赋值和取值来得到想要的Html编码或者解码
*/
<script src=http://www.mamicode.com/"http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>>


<script type="text/javascript">
//获取Html转义字符
function htmlEncode( html ) {
  return document.createElement( 'a' ).appendChild( 
         document.createTextNode( html ) ).parentNode.innerHTML;
};
//获取Html 
function htmlDecode( html ) {
  var a = document.createElement( 'a' ); a.innerHTML = html;
  return a.textContent;
};
</script>

  //编码
    function html_encode(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(/\n/g, "<br>");
        return s;
    }

    //解码
    function html_decode(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(/<br>/g, "\n");
        return s;
    }