JS regular RegExp. test () usage considerations (not repetitive)

Source: Internet
Author: User
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.