+
50
-

jquery和原生js如何对html代码转义后输出?

jquery和原生js如何对html代码转义后输出?


网友回复

+
0
-

jquery的html代码转义

//Html编码获取Html转义实体
function htmlEncode(value){
return $('<div/>').text(value).html();
}
//Html解码获取Html实体
function htmlDecode(value){
return $('<div/>').html(value).text();
}

原生js

<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;
}



by 钱端世界
我知道答案,我要回答