js把预定义的html字符串转换为 HTML 实体 htmlspecialchars 输出html实体内容包括标签,而不自动转义标签,只显示内容,类似php的htmlspecialchars

一、html字符串转换为 HTML 实体 htmlspecialchars

function htmlspecialchars(str){           
          str = str.replace(/&/g, '&');  
          str = str.replace(/</g, '&lt;');  
          str = str.replace(/>/g, '&gt;');  
          str = str.replace(/"/g, '&quot;');  
          str = str.replace(/'/g, '&#039;');  
          return str;  
}  
        
//这个版本多转换了一些内容  
function htmlspecialchars(str) {       
              var s = "";  
              if (str.length == 0) return "";  
              for   (var i=0; i<str.length; i++)  
              {  
                  switch (str.substr(i,1))  
                  {  
                      case "<": s += "&lt;"; break;  
                      case ">": s += "&gt;"; break;  
                      case "&": s += "&amp;"; break;  
                      case " ":  
                          if(str.substr(i + 1, 1) == " "){  
                              s += " &nbsp;";  
                              i++;  
                          } else s += " ";  
                          break;  
                      case "\"": s += "&quot;"; break;  
                      case "\n": s += "<br>"; break;  
                      default: s += str.substr(i,1); break;  
                  }  
              }  
              return s;  
          }

 

二、HTML实体 转换为 html字符串 htmlspecialchars_decode

    将上面的htmlspecialchars中的匹配反过来如:

    function htmlspecialchars_decode(str){           
              str = str.replace(/&amp;/g, '&');
              str = str.replace(/&lt;/g, '<');
              str = str.replace(/&gt;/g, '>');
              str = str.replace(/&quot;/g, "''");  
              str = str.replace(/&#039;/g, "'");  
              return str;  
    }

上一篇:Android手机中怎么样在没root的情况下 修改 hosts 文件


下一篇:PHP htmlspecialchars错误