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

/** JQuery Html Encoding、Decoding
* 原理是利用JQuery自带的html()和text()函数可以转义Html字符
* 虚拟一个Div通过赋值和取值来得到想要的Html编码或者解码
*/
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
//Html编码获取Html转义实体
function htmlEncode(value){
  return $('<div/>').text(value).html();
}
//Html解码获取Html实体
function htmlDecode(value){
  return $('<div/>').html(value).text();
}
</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;
	}
posted @ 2018-01-18 10:08  追忆丶年华  阅读(6606)  评论(0编辑  收藏  举报