Home > Web Front-end > JS Tutorial > The role of parameter g (global) in javascript regular expressions_javascript skills

The role of parameter g (global) in javascript regular expressions_javascript skills

WBOY
Release: 2016-05-16 18:16:27
Original
1173 people have browsed it

We describe in detail:
1) For the exec method of the expression object, if g is not added, only the first match will be returned, no matter how many times it is executed. If g is added, the first match will be returned for the first time. match, then perform the second match, and so on. For example:

Copy code The code is as follows:

var regx=/userd/;
var str="user18duser2dsc";
var rs=regx.exec(str);//The value of rs at this time is {user1}
var rs2=regx.exec(str);//The value of rs at this time The value is still {user1}

If regx=/userd/g:, then the value of rs is {user1} and the value of rs2 is {user2}

Explain through this example: For the exec method, g is added to the expression. It does not mean that all matches can be returned by executing the exec method, but that after g is added, all matches can be obtained in a certain way. The "method" here is for exec , just execute this method.
2) For the test method of the expression object, there is no difference between adding g and not adding g.
3) For the match method of the String object, if g is not added, it will only return the first match. If the match method is always executed, the first match will always be returned. If g is added, all matches will be returned at once. For example:
Copy code The code is as follows:

var regx=/userd/;
var str="user1dge3user2gwe";
var rs=str.match(regx);//The value of rs at this time is {user1}
var rs2=str.match(regx);//The value of rs2 at this time The value is still {user1}

If regx=/userd/g, then the value of rs is {user1, user2}, and the value of rs2 is also {user1, user2}

4) For the replace method of the string object, if g is not added to the expression, only the first match will be replaced. If g is added, all matches will be replaced.

5) For the split method of String object, adding g is the same as not adding g, that is:
Copy code The code is as follows:

var sep=/userd/;
var array=”user1dfsfuser2dfsf”.split(sep);

Then array is The value is {dfsf,dfsf}. When sep=/userd/g, the return value is the same.

6) For the search method of the string object, it is the same whether or not g is added.
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template