字符串的模式匹配方法

2017-06-16 14:46:00
admin
原创
301
<!DOCTYPE html>
<html>
<head>
    <title>String Type Pattern Matching Example</title>
    <script type="text/javascript">
    
        var text = "cat, bat, sat, fat"; 
        var pattern = /.at/;
        
        var matches = text.match(pattern);        
        alert(matches.index);        //0
        alert(matches[0]);           //"cat"
        alert(pattern.lastIndex);    //0

        var pos = text.search(/at/);
        alert(pos);   //1

        var result = text.replace("at", "ond");
        alert(result);    //"cond, bat, sat, fat"

        result = text.replace(/at/g, "ond");
        alert(result);    //"cond, bond, sond, fond"

        result = text.replace(/(.at)/g, "word ($1)");
        alert(result);    //word (cat), word (bat), word (sat), word (fat)
        
        function htmlEscape(text){
            return text.replace(/[<>"&]/g, function(match, pos, originalText){
                switch(match){
                    case "<":
                        return "&lt;";
                    case ">":
                        return "&gt;";
                    case "&":
                        return "&amp;";
                    case "\"":
                        return "&quot;";
                }             
            });
        }
        
        alert(htmlEscape("<p class=\"greeting\">Hello world!</p>")); //&lt;p class=&quot;greeting&quot;&gt;Hello world!&lt;/p&gt;

        var colorText = "red,blue,green,yellow";
        var colors1 = colorText.split(",");      //["red", "blue", "green", "yellow"]
        var colors2 = colorText.split(",", 2);   //["red", "blue"]
        var colors3 = colorText.split(/[^\,]+/); //["", ",", ",", ",", ""]


        
    </script>
</head>
<body>

</body>
</html>
文章分类
联系我们
电话: 18902328227
Email: 2689701946@qq.com
QQ: 2689701946
微信: 18902328227
地址: 广州番禺区繁华路
  • 在线客服
  • 关注微信
  • 联系电话
    • 欢迎咨询
    • 欢迎加入QQ群 303257430
  • 公众号:源宝网络
    • 联系电话及微信号 18902328227