t);
alert(matches.index); //0
alert(matches[0]); //cat
alert(pattern2.lastIndex); //3
matches = pattern2.exec(text);
alert(matches.index); //5
alert(matches[0]); //bat
alert(pattern2.lastIndex); //8
正则表达式的第二个方法是 test(), 它接受一个字符串参数,在模式与该参数匹配的情况下返回true;否则返回false. 在只想知道目标字符串与模式是否匹配时很方便。
4.RegExp 构造函数属性
RegExp 构造函数包含一些属性,这些属性适用于作用域中的所有正则表达式,并且基于所执行的最近一次正则表达式操作而变化。
例子:
var text ="this has been a short summer";
var pattern = /(.)hort/g;
if(pattern.test(text)){
alert(RegExp.input); //this has been a short summer
alert(RegExp.leftContext); //this has been a
alert(RegExp.rightContext); //summer
alert(RegExp.lastMatch): //short
alert(RegExp.lastParen): //s
alert(RegExp.multiline): //false
}