1234newRegExp().source; // "(?:)"newRegExp('\n').source==='\n'; // true, prior to ES5newRegExp('\n').source==='\\n'; // true, starting with ES5
RegExp.prototype.sticky
123456789101112131415161718192021varstr='#foo#';
varregex=/foo/y;
regex.lastIndex=1;
regex.test(str); // trueregex.lastIndex=5;
regex.test(str); // false (lastIndex is taken into account with sticky flag)regex.lastIndex; // 0 (reset after match failure)// When the y flag is used with a pattern, ^ always matches only at the beginning of the input, or (if multiline is true) at the beginning of a line.varregex=/^foo/y;
regex.lastIndex=2;
regex.test('..foo'); // false - index 2 is not the beginning of the stringvarregex2=/^foo/my;
regex2.lastIndex=2;
regex2.test('..foo'); // false - index 2 is not the beginning of the string or lineregex2.lastIndex=2;
regex2.test('.\nfoo'); // true - index 2 is the beginning of a line
123456789101112classMyRegExpextendsRegExp {
// Overwrite MyRegExp species to the parent RegExp constructorstaticget [Symbol.species]() {
returnRegExp;
}
}
constregex1=newMyRegExp('foo','g');
console.log(regex1.test('football'));
// expected output: true
regexp.lastIndex
12345// The lastIndex is a read/write integer property of regular expression instances that specifies the index at which to start the next match.varre=/hello/g;
re.test('hello world!');
RegExp.rightContext; // " world!"RegExp["$'"]; // " world!"
METHODS
RegExp.prototype.exec()
The exec() method executes a search for a match in a specified string. Returns a result array, or null.
123456789101112varmyRe=/ab*/g;
varstr='abbcdefabh';
varmyArray;
while ((myArray=myRe.exec(str)) !==null) {
varmsg='Found '+myArray[0] +'. ';
msg+='Next match starts at '+myRe.lastIndex;
console.log(msg);
}
// Found abb. Next match starts at 3// Found ab. Next match starts at 9
留言
張貼留言