var text = "mom and dad and baby mom and dad";
var pattern = /mom( and dad( and baby)?)?/gi;
var matches = pattern.exec(text);
alert(matches.index); //0
alert(matches.input); //"mom and dad and baby mom and dad"
alert(matches[0]); //"mom and dad and baby"
alert(matches[1]); //" and dad and baby"
alert(matches[2]); //" and baby"
//再次调用exec(),无论接收的字符串是什么,都会从index+matches[0].length的下标开始继续搜索
var matches = pattern.exec(text);
alert(matches.index); // 21
alert(matches.input); //"mom and dad and baby mom and dad"
alert(matches[0]); //"mom and dad"
alert(matches[1]); //" and dad"
alert(matches[2]); //undefined
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.$_); //this has been a short summer
alert(RegExp.leftContext); //this has been a
alert(RegExp["$`"]); //this has been a
alert(RegExp.rightContext); // summer
alert(RegExp["$'"]); // summer
alert(RegExp.lastMatch); //short
alert(RegExp["$&"]); //short
alert(RegExp.lastParen); //s
alert(RegExp["$+"]); //s
alert(RegExp.multiline); //undefined
alert(RegExp["$*"]); //undefined
}
//还有$1~$9分别代表最近的捕获组
alert(RegExp.$10); //undefined
alert(RegExp.$9); //""var text = "this has been a short summer";
var pattern = /(..)or(..)sum(...)/g;
if (pattern.test(text)){
alert(RegExp.$1); //sh
alert(RegExp.$2); //t
alert(RegExp.$3); //mer
alert(RegExp.$4); //""
}
var pattern2 = /(..)or/g;
if (pattern2.test(text)){
alert(RegExp.$1); //sh
alert(RegExp.$2); //"" 此处不会是t 原来的t会被冲掉
alert(RegExp.$3); //"" 同理
alert(RegExp.$4); //""
}