zoukankan      html  css  js  c++  java
  • javascript的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 "
    ": s += "<br>"; break;  
                        default: s += str.substr(i,1); break;  
                    }  
                }  
                return s;  
            }  
  • 相关阅读:
    读《大道至简》第一章有感
    jdk和jre的区别
    题解 LA2911
    题解 UVa11461
    题解 UVa10791
    题解 UVa11489
    题解 LA2889
    题解 UVa11609
    题解 UVa11076
    题解 UVa11752
  • 原文地址:https://www.cnblogs.com/web-leader/p/4742362.html
Copyright © 2011-2022 走看看