Test method test Method Introduction
RegExp.prototype.test(str)
The test method tests for strings in a string parameter that match the regular expression pattern
Use of the test method
let reg = /\w/reg.test(‘a‘) // truereg.test(‘$‘) // false
The result shows that if the test string parameter has a string that matches the regular expression pattern, it returns true, otherwise false
Those pits of the test method
When a regular expression uses a global match, the test method has the following strange behavior:
let reg = /\w/greg.test(‘ab‘) // truereg.test(‘ab‘) // truereg.test(‘ab‘) // falsereg.test(‘ab‘) // true
As you can see, the third match returns to true for each round, but ab not all of them are eligible for Reg, which should return true. The reason lies in the lastindex attribute mentioned in the previous section.
We can try to run the test method each time the Lastindex method is typed in Reg:
let reg = /\w/greg.lastIndex // 0reg.test(‘ab‘) // truereg.lastIndex // 1reg.test(‘ab‘) // truereg.lastIndex // 2reg.test(‘ab‘) // falsereg.lastIndex // 0reg.test(‘ab‘) // truereg.lastIndex // 1
Look at the results, then recall the definition of lastindex, and you'll understand why.
The Lastindex property is the last bit of the final character of the current expression match and is used to specify the starting position of the next match.
When entering the regular expression global pattern, each use of the test method starts with lastindex and matches a substring starting with lastindex. For example, when the test method is executed the second time, Lastindex has become 2 and the substring is empty, so Reg cannot match it. Because the substring match failed, the test method returns false and resets the Lastindex property to 0 to restart the cycle.
Ways to avoid pits in test
The first method: The test method itself is used to test for the existence of a matching regular string, do not use the same as the global schema can achieve the purpose, so the first method is not applicable to the global schema.
The second method: Do not have a regular object instance exists in the variable, each time directly with the regular object instance call test method, but this method of memory loss, theoretically not recommended.
JS Regular expressions from entry to the ground (9) The--test method and its pits