There are two ways to use regular expressions in JS: one is a regular expression object method and the other is a string object method. The former has exec (STR), test (STR) the two methods include match (Regexp), replace (Regexp), search (Regexp), and split (search. When used as a regular expression object method, pay special attention to its lastindex attribute.
VaR Regexp =/ABCD/g; var STR = 'abcdefg'; alert (Regexp. test (STR); // truealert (Regexp. test (STR); // falsealert (Regexp. test (STR); // true
The above sectionCodeThe running results are true, false, and true respectively. Considering that the same regular mode is used, is it a bit confusing?
In fact, this is the lastindex attribute of the regular expression object. Lastindex is literally the last index. In fact, it indicates the index location where the regular expression starts the next query. It is always 0 for the first query, when the first query is complete, the value of lastindex is set to the index location of the last character matching the string plus 1. The second query starts from the location of lastindex, and so on. If no value is found, the lastindex is reset to 0. It should be noted that the lastindex attribute only works in a global sign regular expression. If we remove the G sign of the regular expression in the code above, all the three pop-up events will be true.
The Exec () method is the same. The Exec () method returns an array. The first element of the array is the matched string, and the subsequent elements correspond to the matched strings respectively, that is, those enclosed in parentheses in the regular expression. If the regular expression using the exec () method does not have a global sign, it will only match the first one. If the regular expression has a global sign, you can use exec () cyclically to obtain all the matches, until exec () returns NULL, that is, no matching is found. Here, we can use the exec () method of the same regular expression cyclically, relying on lastindex, because the regular expression with the global flag will update the value of lastindex after each match as the starting point for the next match.
The last note is that the lastindex attribute does not work in the string's regular expression method, regardless of whether the regular expression mode is global or not.