In fact, I seldom use this, so I have not been aware of this problem, since the leaves of the man wrote a perverted test I went to see this thing.
Let's take a look at something first.
var /\d/, Console.log (Re.test ("1")), Console.log (Re.test ("1")), Console.log (Re.test ("1 ")); Console.log (Re.test (" 1 "));
All is true no problem.
But you put /\d/; Change into /\d/g; Try again.
Modify again:
/\d/g. Test ("1"/\d/g. Test ("1"/\d/g. Test ("1"/\d/g . Test ("1"));
All is true, what exactly is this for?
These results are quite interesting, of course, the master naturally know why, if you know, the following can actually skip without looking, all is hydrology only.
There is a LastIndex attribute in the regular, which is the starting position of the next match.
var /\d/g, Console.log (Re.test ("1"), Re.lastindex), Console.log (Re.test ("1"), Re.lastindex) ; Console.log (Re.test ("1"), Re.lastindex) Console.log (Re.test ("1"), Re.lastindex);
You can see that the first match result is true to indicate a successful match, at which point the lastIndex records the next match starting at 1.
So the second match of the time from the "1" string index 1 of the position matching, of course, the match failed, because the string has only one character, his index is 0.
and /\d/g. Test ("1") why does each match succeed?
Because it directly uses regular literals, equivalent to recreating a regular object each time, theLastIndex property is the initial value of 0.
So every time we can match the success.
Now is not understood, including exec also, each match one,LastIndex record the next match start position.
If a regular object is to be used, it is only necessary to reset the lastIndex before each test so that he does not get out.
var /\d/g, Console.log (Re.test ("1"0; Console.log (Re.test ("1"0; Console.log (Re.test ("1"0; Console.log (Re.test ("1"));
Well, today to modify the syntax highlighting plugin took a lot of time, so water a piece, hope everyone haihan.