Before using JS in the process of the expression, the basic is to use the test method, exec seldom use, let alone test and exec mixed situation, today happened to encounter this situation, so found a small ' bug '.
For example, we would like to match the full text with a length of 4 words, which we will usually do:
var str = ' My last name is Junhua 'var reg =/\b\w{4}\b/gvar result, = 1
while (i > 0
) { =
reg.exec (str)
if(!
Result) { break
; } Console.log (Result)}
The result of printing is last and name, which is what we want, but what happens if we call test once before?
var str = ' My last name is Junhua 'var reg =/\b\w{4}\b/gconsole.log (reg.test (str))var result, = 1 while (i > 0) { = reg.exec (str) if(! Result) { break; } Console.log (Result)}
The result is only the name of the print, so where did our last go? Let's consider what the function of test is, is to judge whether our string matches the regular, then when we encounter the last, our result is true, it's a match, At this point we print the value of the Reg.lastindex in the code, the value is 7, here to explain the lastindex value, lastIndex is an integer, indicating the beginning of the search for the next occurrence of the character position, from 0. See here is not an epiphany, and then the next match, our search is from 7 This position began, so naturally no last only name, then we take this small ' bug ' is very simple.
var str = ' My last name is Junhua 'var reg =/\b\w{4}\b/= 0; var result, = 1 while (i > 0) { = reg.exec (str) if(! Result) { break; } Console.log (Result)}
Set the lastindex value of Reg to the initial value of 0.
Although exec and test are two methods, they appear to be moving the RegExp instance attribute lastindex, which needs to be noted.
A small ' conflict ' between Exex () and test () for instance methods of RegExp in JavaScript