“`
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
<style type="text/css">
#textarea {
width: 500px;
height: 500px;
margin: 0 auto;
}
</style>
<textarea id="textarea">
</textarea>
<!-- <script type="text/javascript"> alert("我是javascript代碼!");</script> -->
<button id="re">轉義</button> <button id="re2">反轉義</button>
<h4>轉義</h4>
<p id="show"></p>
<h4>反轉義</h4>
<p id="show2"></p>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
(function(w){
function Demo() {
var _this = this;
_this.init = function() {
_this.bindEvent();
};
_this.bindEvent = function() {
$("#re").click(function() {
var str = $("#textarea").val();
str = _this.unhtml(str);
$("#show").text(str); //要注意這裏都是text方法哈。
});
$("#re2").click(function() {
var str = $("#textarea").val();
str = _this.html(str); //這個html方法是這個對象的。不是jq的html方法
$("#show2").text(str); //要注意這裏都是text方法哈。
//假設後臺返回過來的數據時經過轉義的
//<script type="text/javascript"> alert("我是javascript代碼!");</script>
//前端顯示直接 用jq的html方法顯示到頁面上就行了。不要用text方法,也不需要自己轉義哈。切記!切記!
});
};
};
Demo.prototype = {
_this: this,
/**
* 將str中的html符號轉義,將轉義“',&,<,",>”五個字符
* @method unhtml
* @param { String } str 需要轉義的字符串
* @return { String } 轉義後的字符串
* @example
* ```javascript
* var html = '<body>&</body>';
*
* //output: <body>&</body>
* console.log( UE.utils.unhtml( html ) );
*
* ```
*/
unhtml:function (str, reg) {
return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp|#\d+);)?/g, function (a, b) {
if (b) {
return a;
} else {
return {
'<':'<',
'&':'&',
'"':'"',
'>':'>',
"'":'''
}[a]
}
}) : '';
},
/**
* 將str中的轉義字符還原成html字符
* @see UE.utils.unhtml(String);
* @method html
* @param { String } str 需要逆轉義的字符串
* @return { String } 逆轉義後的字符串
* @example
* ```javascript
*
* var str = '<body>&</body>';
*
* //output: <body>&</body>
* console.log( UE.utils.html( str ) );
*
* ```
*/
html:function (str) {
return str ? str.replace(/&((g|l|quo)t|amp|#39|nbsp);/g, function (m) {
return {
'<':'<',
'&':'&',
'"':'"',
'>':'>',
''':"'",
' ':' '
}[m]
}) : '';
}
}
w.Demo = Demo;
})(window)
var demo = new Demo();
demo.init();
</script>
</body>
</html>
附上兩張效果圖
將html標籤轉義
將html標籤轉義後字符串反轉義成html標籤
這裏有防js代碼注入的文章
. 防js代碼注入 http://blog.csdn.net/wx11408115/article/details/78201544