2
var re1=new RegExp("","g");
var str1="a";
console.log(str1.match(re1));

var re2=new RegExp("","g");
var str2="a";
console.log(re2.exec(str2));
console.log(re2.exec(str2));

why the first will capture two empty string,and the second can only contain one empty string?

Ry-
  • 218,210
  • 55
  • 464
  • 476
cutemurphy
  • 23
  • 2
  • @Vache: `match` will return all results, but `exec` will only ever return one. I think your edit invalidates the question. – icktoofay Jan 04 '14 at 02:48
  • @icktoofay Yeah I completely misunderstood what was meant in the question. Sorry about that. – dee-see Jan 04 '14 at 02:50
  • possible duplicate of [What is the difference between javascripts regex exec() function and string match() function?](http://stackoverflow.com/questions/9214754/what-is-the-difference-between-javascripts-regex-exec-function-and-string-matc) – Daniel A. White Jan 04 '14 at 02:52
  • @Daniel: Not quite. You should usually be able to replace a call to `match` with an `exec` loop; in this case, however, they yield different results, and that's what the question is about. – icktoofay Jan 04 '14 at 02:53

1 Answers1

2

In short: it doesn’t.

js> var re1 = new RegExp("", "g");
js> var str1 = "a";
js> str1.match(re1)
["", ""]
js> var re2 = new RegExp("", "g");
js> var str2 = "a";
js> re2.exec(str2)
[""]
js> re2.exec(str2)
[""]

Each of these [""]s is a result, as exec is meant to be called in a loop and retrieve both all matches and all groups, as in:

var pairs = /(.).*?\1/g;
var input = "._.  ^.^ -__-";
var match;

while (match = pairs.exec(input)) { // exec() returns null on /g regexes when there are no more matches
    console.log(match);
}

A more interesting question might be why re2.lastIndex doesn’t change after matching, so you can get the same match forever and it’ll never be null. Well, that’s just because it advances by the length of the match for each match, and here the length is zero.

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • u can continue to run the re2.exec(str2) and will get the same result,but re2.lastIndex's result never changed,why? var re2=new RegExp("","g"); var str2="a"; console.log(re2.exec(str2),re2.lastIndex); console.log(re2.exec(str2),re2.lastIndex); console.log(re2.exec(str2),re2.lastIndex); – cutemurphy Jan 04 '14 at 02:58
  • .nice answer and nice person..haha – cutemurphy Jan 04 '14 at 03:18