Lastindex property of the global identity regular expression in [JavaScript] js

Source: Internet
Author: User

When using regular expressions in JavaScript, a pit is encountered: The first match is true, and the second match is false.

Because there is a "LastIndex" property in a regular expression object with the global identity "G", this property is used to specify the starting position of the next match.

For example:

var New // with global identity var New // with no global identity

With the global identity of the regular pattern1, after the string is matched to the substring, the value of Pattern1.lastindex is not immediately reset to 0, but the last matching position continues to look backwards to see if there is a matching value, which can cause the problem: " A matching string matches the first time to true, and the second match is false.

There are two ways to resolve this:
(1) The Global Identity "G" is removed, and a regular expression is defined with a string wrapped in [^][$] end-to-end qualifier;
(2) In some cases, the global identity "G" must be preserved, you can manually reset the value of lastindex to 0 after a match (test), such as:

Pattern1.lastindex = 0

Lastindex property of the global identity regular expression in [JavaScript] js

Related Article

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.