0

I'm a beginner in Javascript, and was playing around with regular expressions.

I tried to perform some matching operation but the result is quite confusing.

All what i'm trying to do is to match every website name in :

"I go to google.com to search, to facebook.com to share and to yahoo.com to send an email."

Here's my code :

var text = "I go to google.com to search, to facebook.com to share and to yahoo.com to send an email.";
var pattern = /\w+\.\w+/g;

var matches = pattern.exec(text);

document.write("matches index : " + matches.index + "<br>");
document.write("matches input : " + matches.input + "<br>");
document.write("<br>");
for(i=0 ; i<matches.length ; i++){
    document.write("match number " + i + " : " + matches[i] + "<br>");
}

And my result :

matches index : 0

matches input : i go to google.com to search, to facebook.com to share and to yahoo.com to send an email

match number 0 : google.com

Why does it match google.com only, and not the other websites ?

Rafael Adel
  • 7,673
  • 25
  • 77
  • 118
  • possible duplicate of [How do I retrieve all matches for a regular expression in JavaScript?](http://stackoverflow.com/questions/6323417/how-do-i-retrieve-all-matches-for-a-regular-expression-in-javascript) – Felix Kling Jul 12 '12 at 00:39

2 Answers2

1

From the MDN documentation:

If your regular expression uses the "g" flag, you can use the exec method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test will also advance the lastIndex property).

So, just execute it multiple times:

var match, i = 0;
while(match = pattern.exec(text)) {
    document.write("match number " + (i++) + " : " + match[0] + "<br>");
}

or, since you don't have capture groups, use .match():

var matches = text.match(pattern);
for(i=0 ; i<matches.length ; i++){
    document.write("match number " + i + " : " + matches[i] + "<br>");
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Hmmm, weird though. In [Professional Javascript for web developers](http://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=pd_sim_b_1) book. There's an example [here](http://jsfiddle.net/smokn/gzAVS/) using exec only one time. And the weird thing that it works ! – Rafael Adel Jul 12 '12 at 00:50
  • @Rafael - The example in your fiddle uses capturing groups `( ... )` – Stephen P Jul 12 '12 at 00:55
  • In your last example when there are no matches the for loop will generate an error. So better check if `matches` is not null first. – inhan Jul 12 '12 at 01:01
0

I just wanted to mention that the replace method is sometimes a better fit to iterate through a string, even if you don't actually intend to replace anything.

Here is how it could work in your case:

var matches = text.replace(pattern,function($0){alert($0);});

Live demo here

Christophe
  • 27,383
  • 28
  • 97
  • 140