Home >Web Front-end >JS Tutorial >Precautions for using JS regular RegExp.test() (not repetitive)
The example of this article analyzes the precautions for using JS regular RegExp.test(). Share it with everyone for your reference, the details are as follows:
First look at the following code:
// 2012-12-12 12:12:12 var regex = /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/g; // true alert(regex.test("2012-12-12 12:12:12")); // false alert(regex.test("2012-12-12 12:12:12"));
The execution results are already in the code comments, you can see: For the same regular expression object Regex cannot be called repeatedly: it returns true for the first time and false for the second time. Obviously this effect is not what we want. This is because the RegExp.test() method starts the search from position 0 for the first time and can match; the second search position is not 0, so it cannot match.
The solution is quite simple: just let the test start matching from the 0th position every time:
// 2012-12-12 12:12:12 var regex = /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/g; // true alert(regex.test("2012-12-12 12:12:12")); regex.lastIndex = 0; // true alert(regex.test("2012-12-12 12:12:12"));
I hope this article will be helpful to everyone in JavaScript programming.
For more JS regular RegExp.test() usage precautions (not repetitive), please pay attention to the PHP Chinese website!