Home > Web Front-end > JS Tutorial > Precautions for using JS regular RegExp.test() (not repetitive)

Precautions for using JS regular RegExp.test() (not repetitive)

高洛峰
Release: 2017-01-09 15:23:36
Original
1643 people have browsed it

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"));
Copy after login

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"));
Copy after login

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!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template