字符串的模式匹配方法

1.match()  本质上与调用RegExp的exec()方法相同。

 var text = "cat, bat, sat, fat";
    var pattern = /.at/;
    
    //与pattern.exec(text)相同
    var matches = text.match(pattern);
    console.log(matches.index);     //0
    console.log(matches.input);     
    console.log(matches[0]);        //"cat"
    console.log(pattern.lastIndex); //0

2.search()  返回字符串中第一个匹配项的索引;没有则返回-1,始终从头查找。

    var text = "cat, bat, sat, fat",
        pos = text.search(/at/);
    console.log(pos);               //1

3.replace()  替换字符串操作。接受两个参数。

a.如果第一个参数是字符串,那么只会替换第一个子字符串。要想替换所有子字符串,唯一的办法是提供一个全局标志。

var text = "cat, bat, sat, fat",
    result = text.replace("at", "ond");
console.log(result);    //"cond, bat, sat, fat"
    
result = text.replace(/at/g, "ond");
console.log(result);    //"cond, bond, sond, fond"

b.如果第二个参数是字符串,那么还可以加入一些特殊的字符序列。

var text = "cat, bat, sat, fat";
result = text.replace(/(.at)/g, "word ($1)");
console.log(result);    

c.第二个参数也可以是函数。

  • 在只有一个匹配项的情况下,会向这个函数传递3个参数:模式的匹配项、模式匹配项在字符串中的位置和原始字符串。
  • 在正则表达式中定义了多个捕获组的情况下,传递给函数的参数依旧是模式的匹配项、第一个捕获组的匹配项、第二个......,但是最后两个参数依旧是不变的。
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;";
            }
        })
    }

    console.log(htmlEscape("<p class=\"greeting\"> Hello world! </p>"));
    //&lt;p class=&quot;greeting&quot;&gt; Hello world! &lt;/p&gt;

4.  split()  这个方法可以基于指定的分隔符将一个字符串分割成多个子字符串,并将结果放在一个数组中。分隔符可以是字符串,也可以是一个RegExp对象。

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

/[^\,]+/  表示不是逗号的连续字符 

猜你喜欢

转载自www.cnblogs.com/CZheng7/p/12616193.html