This article mainly introduces the JS regular RegExp. test () usage considerations, combined with the instance form analysis RegExp. the functions and usage of the test () method and the solution that cannot be called repeatedly can be used. If you need it, refer to the example in this article to analyze the JS regular RegExp. notes for using test. We will share this with you for your reference. The details are as follows:
Let's take a look at the following code:
// 2012-12-12 12: 12: 12var regex =/\ d {4}-\ d {2}-\ d {2} \ d {2}: \ d {2 }: \ d {2}/g; // truealert (regex. test ("12:12:12"); // falsealert (regex. test ("12:12:12 "));
The execution result is already in the code comment. We can see that for the regex object of the same regular expression, it cannot be called repeatedly: true is returned for the first time, and false is returned for the second time, obviously, this effect is not what we want. This is because the RegExp. test () method can be matched for the first time from the position 0. The second time is not 0, so it cannot be matched.
The solution is quite simple: each time test is matched from the first position:
// 2012-12-12 12: 12: 12var regex =/\ d {4}-\ d {2}-\ d {2} \ d {2}: \ d {2 }: \ d {2}/g; // truealert (regex. test ("12:12:12"); regex. lastIndex = 0; // truealert (regex. test ("12:12:12 "));
I hope this article will help you design JavaScript programs.
For more articles about JS regular RegExp. test () usage notes (not repetitive), please pay attention to PHP!