The role of parameter G (global) in JavaScript regular expressions _javascript tips

Source: Internet
Author: User
We describe in detail:
1 for the Exec method of the expression object, do not join G, return only the first match, no matter how many times the execution is so, if you add G, then the first execution returns the first match, then the second match, and so on. For example:
Copy Code code as follows:

var regx=/user\d/;
var str= "USER18DUSER2DSC";
var rs=regx.exec (str);//This time the value of Rs is {user1}
var rs2=regx.exec (str);//At this time the value of Rs is still {user1}

If regx=/user\d/g: The value of RS is {User1},rs2 is {user2}

This example illustrates that, for the Exec method, the expression adds G, not that the Exec method can return all matches, but that after the addition of G, there is a way to get all the matches, and the "way" for exec is to execute this method.
2 for the test method of an Expression object, adding G to no g is no different.
3 for the match method of a String object, no G, just return the first match, the match method always returns the first match, joins G, and returns all matches at once. For example:
Copy Code code as follows:

var regx=/user\d/;
var str= "User1dge3user2gwe";
var rs=str.match (REGX);//This time the value of Rs is {user1}
var rs2=str.match (REGX);//At this point the value of Rs2 is still {user1}

If regx=/user\d/g, then the value of RS is {User1,user2},rs2 value is also {User1,user2}

4 for the Replace method of a String object, the expression does not add G, only the first match is replaced, and if G is added, all matches are replaced.

5 for the string object's Split method, plus G and no g are the same, namely:
Copy Code code as follows:

var sep=/user\d/;
var array= "USER1DFSFUSER2DFSF". Split (Sep);

The value of the array is {DFSF,DFSF}, and the return value is the same when sep=/user\d/g.

6 for a String object search method, plus g is the same.
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.