正则---让人喜欢让人忧(7)

支持正则表达式的String对象方法:

  字符串方法有:search    match     replace     split 

  1.  search:返回匹配文本第一个字符索引;找不到返回 -1;

       自动忽略全局匹配;忽略lastIndex属性,从字符串开始检索。

       stringObject.search(regexp);

  2. match: 一个或多个正则表达式的匹配,检索指定的值;

      存放匹配结果的数组。数组内容依赖于RegExp是否具有全局标志"g";

      stringObject.match(searchvalue);

      stringObject.match(regexp);   //不是正则对象,传递给RegExp构造函数将其转换为RegExp对象;

           var matStr="Hello world!";
            var mat=matStr.match("H");   
            log(mat);      //["H", index: 0, input: "Hello world!"]
            var matt = matStr.match(/l/g);
            log("全局模式"+matt);    //全局模式["l", "l", "l"]

  3.  replace:  执行的是查找并替换的操作

      stringObject.replace(regexp/substr,replacement)  

        //substr:直接量文本模式,不转换正则对象    replacement:替换文本或替换文本的函数

        

                //replacement中  $具有特殊的含义。
                //$1、$2、...、$99    与 regexp 中的第 1 到第 99 个子表达式相匹配的文本。
                //$& 与 regexp 相匹配的子串。
                var name = "Doe, John";
                // document.write(name.replace(/(w+)s*, s*(w+)/,"$2 $1"));  //"John Doe"

         // ["Doe, John", "Doe", "John", 0, "Doe, John", callee: ƒ, Symbol(Symbol.iterator): ƒ]
          name.replace(/(w+)s*, s*(w+)/,function(){ log(arguments); //该函数的第一个参数是匹配模式的字符串。接下来的参数是与模式中的子表达式匹配的字符串,可以有 0 个或多个这样的参数。接下来的参数是一个整数,声明了匹配在 stringObject 中出现的位置。最后一个参数是 stringObject 本身。 }) //如何使用 replace() 确保大写字母的正确性。 var text = "javascript Tutorial"; text.replace(/javascript/i, "JavaScript"); //花引号转为直引号 var name1 = '"a", "b"'; document.write(name1.replace(/"([^"]*)"/g, "'$1'")); log(name1); //我们将把字符串中所有单词的首字母都转换为大写: var name2 = 'aaa bbb ccc'; var uw=name2.replace(/w+/g, function(word){ return word.substring(0,1).toUpperCase()+word.substring(1); // log(arguments[0]) 匹配的字符 // log(arguments[1]) 匹配字符的索引 // log(arguments[2]) stringObject本身 });

    

  4.split:  把字符串分割成字符串数组  

      stringObject.split(separator,howmany)

      

      提示和注释:  如果把空字符串("")用作separator,那么 stringObject中的每个字符之间都会被分割。

             String.split() 执行的操作与 Array.join执行的操作是相反的。

                    var splitStr="How are you doing today?"
                    document.write(splitStr.split(" ") + "<br />") //["How","are","you","doing","today?"]
                    document.write(splitStr.split("") + "<br />")//["H", "o", "w", " ", "a", "r", "e", " " , "y", "o", "u", " ", "d", "o", "i", "n", "g", " ", "t", "o", "d", "a", "y", "?"]
                    document.write(splitStr.split(" ",3)) //["How", "are", "you"]
                    
                    "2:3:4:5".split(":")    //将返回["2", "3", "4", "5"]
                    "|a|b|c".split("|")       //将返回["", "a", "b", "c"]

        正则对象的属性

      

      

原文地址:https://www.cnblogs.com/baota/p/7446132.html