JavaScript转义HTML的方法
(function(){
this.encodeHtml = function(str){
var s = "";
if (str.length == 0) return "";
s = str.replace(/&/g, "&");
s = str.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;
};
this.decodeHtml = function(str){
var s = "";
var s = "";
if (str.length == 0) return "";
s = str.replace(/&/g, "&");
s = str.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;
};
})();
调用window.encodeHtml(要转义的字符),获取转义的结果。
调用window.decodeHtml (转义的字符),获取反转义的结果。