Rafael Adel
Rafael Adel

Reputation: 7759

Simple regular expression issue

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 ?

Upvotes: 0

Views: 74

Answers (2)

Christophe
Christophe

Reputation: 28124

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

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816422

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>");
}

Upvotes: 1

Related Questions