Home  >  Article  >  Web Front-end  >  JavaScript regular expression exec/g implements multiple loop usage examples

JavaScript regular expression exec/g implements multiple loop usage examples

高洛峰
高洛峰Original
2017-01-20 13:58:281672browse

The example in this article describes the use of JavaScript regular expression exec/g to implement multiple loops. Share it with everyone for your reference, the details are as follows:

var x = "a.xxx.com b.xxx.com c.xxx.com";

Hope to get the three results of ["a", "b", "c"]

1. Regular needs to add g

2. exec loop until empty is returned

The code is as follows, it will output a b c

var x = "a.xxx.com b.xxx.com c.xxx.com";
var re = /\s?(.*?).xxx.com/g;
while( tempR = re.exec(x))
{
 console.log(tempR[1]);
}

The function of exec is more powerful than match

Tip: Note that regardless of whether the RegExpObject is global or not, exec() will add the full details to the array it returns. This is where exec() differs from String.match(), which returns much less information in global mode. So we can say that calling the exec() method repeatedly in a loop is the only way to get complete pattern matching information for the global pattern.

I hope this article will be helpful to everyone in JavaScript programming.

For more JavaScript regular expression exec/g implementation of multiple loop usage examples, please pay attention to the PHP Chinese website!

Statement:
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