Regular expression test (), using g__ regular expressions with caution
Source: Internet
Author: User
Today, when this expression is presented, a problem is found:
Test () detects whether a specified string exists and returns a Boolean value
var reg=/cat/g;
var str= ' This a cat,this a dog ';
document.write (Reg.test (s));
document.write (Reg.test (str));
According to the reason two times print out should be true,true, and the end result is true,false.
At this point we need to be aware that the search is added to the regular expression we defined, and that G represents the Full-text lookup. And there is a lastindex within the regular expression to record the matching position, and after the first call to test (), then the lastindex is no longer equal to 0, but 10, and the next time the method is called, the string match is matched from the lastindex position. So the end returns false. So don't add g at random.
How to resolve this situation:
1. Remove G;
2. Before using the second time, set reg.lastindex=0.
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