Regular test () that is caused by misuse of/g in JavaScript _javascript tips for a solution that cannot be executed correctly and repeatedly

Source: Internet
Author: User

A simple use is to determine whether the input is a number:

INPUT1 = ' 0281234567 '; input2 = ' 0282345678 '; var reg =/^\d+$/g;
Reg.test (INPUT1); True

The value returned when the second Test was found was incorrect. Excluding writing errors, value failures, and so on all kinds of interference factors, found that only Reg is the second execution of the time can not be executed correctly. I have not encountered this problem before, then searched the relevant information.

It turns out that this problem was actually caused by/g, and this time it was discovered that, in fact, I misused a/g. Because the/g represents a global match, there is a lastindex to record the last matching position within the regular time. When repeated calls, will then continue to match the last lastindex, which will result in errors in judgment. Understand the principle of the solution is very clear:

1. Remove/g, do not need to/g to add/g logo

2. Before the second match, manually lastindex 0, in the above example: Reg.lastindex () =0 can be.

The above mentioned is a small set of JavaScript to introduce the misuse of/g caused by the regular test () can not be correctly repeated implementation of the solution, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.