HTML转义为实体,实体转回为HTML,特殊字符转换

时间:2021-12-03 20:21:08
/**
 * 将HTML转义为实体
 */
String.prototype.escapeHtml=function(){
    var s = "";
    if(Utils.isNullorEmpty(this)) return "";
    s = this.replace(/&/g, "&");
    s = s.replace(/</g, "&lt;");
    s = s.replace(/>/g, "&gt;");
    s = s.replace(/ /g, "&nbsp;");
    s = s.replace(/\'/g, "&#39;");
    s = s.replace(/\"/g, "&quot;");
    s = s.replace(/\n/g, "<br>");
    return s;
}

/**
 * 将实体转回为HTML
 */
String.prototype.unescapeHtml=function(){
    var s = "";
    if(Utils.isNullorEmpty(this)) return "";
    s = this.replace(/&amp;/g, "&");
    s = s.replace(/&lt;/g, "<");
    s = s.replace(/&gt;/g, ">");
    s = s.replace(/&nbsp;/g, " ");
    s = s.replace(/&#39;/g, "\'");
    s = s.replace(/&quot;/g, "\"");
    s = s.replace(/<br>/g, "\n");
    return s;
}
// 判断字符是否为空
Utils.isNullorEmpty=function(str){
  if((str==null||str==""||str==undefined||str=="undefined")&&(str!=0||str!="0"))
    return true;
  else
    return false;
}