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; }
相关推荐
EdwardSiCong 2020-11-23
85477104 2020-11-17
hhanbj 2020-11-17
81427005 2020-11-11
seoppt 2020-09-13
honeyth 2020-09-13
WRITEFORSHARE 2020-09-13
84483065 2020-09-11
momode 2020-09-11
85477104 2020-08-15
83510998 2020-08-08
82550495 2020-08-03
tthappyer 2020-08-03
84901334 2020-07-28
tthappyer 2020-07-25
TONIYH 2020-07-22
tztzyzyz 2020-07-20
83510998 2020-07-18
81463166 2020-07-17