5、str.split(RegExp[,limit]) 将字符串str用符合匹配的字符串分割成数组,limit 可选,用于限定返回的数组长度 ("ada2afa4fcas6afa").split(/d/,3) // "ada,afa,fcas" 6、RegExp.exec("str") 方法 在str中查找匹配的字符串,注意,每次运行该方法只匹配一次,要匹配多个需要将RegExp设置为/g,并多次运行exec()方法,每次匹配返回值 result = RegExp.exec("str") result为一个数组,这个数组长度为1,数组元素为找到的匹配的子串, 另外,这个数组被额外赋给了2 个属性: result.index 表示匹配的子串在原字符串的开始位置 result.input 就是原字符串 当再也无法找到符合匹配的子串时,返回 result = null,并设置 RegExp.lastIndex=0 RegExp.lastIndex 是正则表达式的属性,表示当前将从字符串的哪个位置开始匹配,初始值为0。 如果RegExp被设置为全局的,在匹配一个字符串一次之后,使用同一个RegExp对一个新的字符串进行匹配请先手动设置 RegExp.lastIndex=0 如果RegExp 不是全局匹配模式,在程序中又写了一个循环,根基返回值 result来决定是否终止匹配,从而试图匹配完这个字符串,那么,只要有符合匹配条件的子串,就必定造成死循环,因为非全局匹配只对字符串匹配一次,结果每次运行匹配操作都是匹配第一个子串,返回的 result 不为空,这是个比较容易犯的错误。 复制代码 代码如下: var str = "1Visit W3School, W3School is a place to study web technology."; var patt = new RegExp("W3School","g"); var result; document.write(patt.lastIndex+"<br />"); document.write("=====================================<br />"); while ((result = patt.exec(str)) != null) { document.write(patt.lastIndex+"<br />"); document.write(result.constructor.name+"<br />"); document.write(result.length+"<br />"); document.write(result[0]+"<br />"); document.write(result.index+"<br />"); document.write(result.input+"<br />"); document.write("=====================================<br />"); } document.write(patt.lastIndex+"<br />"); // 运行结果: ===================================== Array W3School Visit W3School, W3School is a place to study web technology. ===================================== Array W3School Visit W3School, W3School is a place to study web technology. =====================================
7、RegExp.test("str") 方法 该方法与 RegExp.exec 类似,不同的是仅返回true或false RegExp.lastIndex 的含义是一样的(这是RegExp的属性,跟是使用test方法还是exec方法无关) 如果同一个RegExp 先后使用了test方法和exec方法,你可能需要手动设置 RegExp.lastIndex=0,这些方法是共享同一个RegExp对象的lastIndex 属性的 复制代码 代码如下: var str = "1Visit W3School, W3School is a place to study web technology."; var patt = new RegExp("W3School","g"); var result ; result = patt.test(str); alert(result); //true result = patt.test(str); alert(result); //true result = patt.test(str); alert(result); //false