let text = "mom and dad and baby"; let pattern = /mom( and dad( and baby)?)?/gi; let matches = pattern.exec(text); console.log(matches.index); // 0 console.log(matches.input); // "mom and dad and baby" console.log(matches[0]); // "mom and dad and baby" console.log(matches[1]); // " and dad and baby" console.log(matches[2]); // " and baby"
let text = "this has been a short summer"; let pattern = /(.)hort/g; if (pattern.test(text)) { console.log(RegExp.input); // this has been a short summer console.log(RegExp.leftContext); // this has been a console.log(RegExp.rightContext); // summer console.log(RegExp.lastMatch); // short console.log(RegExp.lastParen); // s } //==============等价于============== let text = "this has been a short summer"; let pattern = /(.)hort/g; /* * 注意:Opera 不支持简写属性名 * IE 不支持多行匹配 */ if (pattern.test(text)) { console.log(RegExp.$_); // this has been a short summer console.log(RegExp["$`"]); // this has been a console.log(RegExp["$'"]); // summer console.log(RegExp["$&"]); // short console.log(RegExp["$+"]); // s }