Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

regex - JavaScript regular expression with global match help needed

I'm new to JavaScript and have a question about regular expressions. I have the following code:

var patt3=new RegExp(/(July|August)s+d{1,2}(s|,)d{4}/g);
var str3 = "August                               12,1988";
var match3 = str3.match(patt3);
document.write(match3.toString() + "<br/>");

The output is: August 12,1988

Here is the same code but with the 'g' removed from the end of the RegExp:

var patt3=new RegExp(/(July|August)s+d{1,2}(s|,)d{4}/);
var str3 = "August                               12,1988";
var match3 = str3.match(patt3);
document.write(match3.toString() + "<br/>");

The output becomes: August 12,1988,August,,

From the definitions that I've found on the web, 'g' is supposed to match all occurrences of the patterns. But I'm still kind of confused as to what effect 'g' has on the code.

I would greatly appreciate any clarifications.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The crucial difference is that the string.match method is defined to have a different behavior if the regex patter is global or not.

If the pattern is global, an array with all the matches. In your case you there is only one match but you can see the difference with an example like

let matches = "aaaa".match(/a(a)/g); 
console.log(matches) // returns ["aa", "aa"]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...