Blogger Information
Blog 7
fans 1
comment 0
visits 11008
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
js html标签实体转化
漫漫人生路
Original
1228 people have browsed it

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


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post