Skip to content

Instantly share code, notes, and snippets.

@zhuzhuaicoding
Created September 20, 2012 13:29
Show Gist options
  • Select an option

  • Save zhuzhuaicoding/3755911 to your computer and use it in GitHub Desktop.

Select an option

Save zhuzhuaicoding/3755911 to your computer and use it in GitHub Desktop.
check the change of lastIndex,and in greedy match what the result like.<http://jsfiddle.net/earlybird/RrZKH/2/>
//1.with greedy match and global flag
var re = /\s*/g;
for (var i = 0; i < 6; i++) {
console.log(re.exec(' as '));
console.log(re.lastIndex);//4,4,4,4,4,4
}
//2.without greedy match ,but global flag
var re1 = /\s/g;
for (var i = 0; i < 6; i++) {
console.log(re1.exec(' as '));
console.log(re1.lastIndex);//1,2,3,4,7,8
}
//3.match failed, without greedy match ,but global flag
var re2 = /\s*/g;
for (var i = 0; i < 6; i++) {
console.log(re2.exec('as'));//''(empty string),...
console.log(re2.lastIndex);//0,0,0,0,0,0
}
//4.match failed, without greedy match ,but global flag
var re3 = /\s/g;
for (var i = 0; i < 6; i++) {
console.log(re3.exec('as'));// null ...
console.log(re3.lastIndex);//0,0,0,0,0,0
}​
/***********************************************************************/
var re = /hi?/g;
for(var i = 0;i<10;i++){
re .exec('hi');
console.log(re.lastIndex); // 2,0,2,0,2,0,2,0,2,0
}
var re = /(hi)?/g;
for(var i = 0;i<10;i++){
re .exec('hi');
console.log(re.lastIndex);//2,2,2,2,2,2,2,2,2,2
}
the diff between non-parentheses and parentheses.
@zhuzhuaicoding

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment