0

This must habe been asked a million times, but I can't find a solution to fit my needs.

I need to regex to check if a string contains an url, then get it. So I have this :

    var regexToken = /(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)|((mailto:)?[_.\w-]+@([\w][\w\-]+\.)+[a-zA-Z]{2,3})/g;

    while( (matchArray = regexToken.exec( source )) !== null )
    {
        var result = matchArray[0];

    }

    return result;

This can retrieve :

But I need to modify that so it could also retrieve url that just begin with www :

  • www.domain.com/with/path

How to do that ? I'm really noob with regex...

enguerranws
  • 8,087
  • 8
  • 49
  • 97

2 Answers2

0

Something like this may help:

/(((ftp|https?):\/\/|www\.)[continue from here]/

This will start matches allowing ftp://, http://, https:// or www.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

Try this way to match url of different format.Like,

 var re = /^((ftp|https?):\/\/|www\.).*/gm;
    var str = 'http://domain.com\nhttps://domain.com\nftp://domain.com\nftp://www.domain.com\nhttp://www.domain.com\nhttps://www.domain.com\nhttp://www.domain.com/with/path\nhttps://www.domain.com/with/path\nftp://www.domain.com/with/path\nwww.domain.com/with/path \n\n';
    var m;

    while ((m = re.exec(str)) != null) {
    if (m.index === re.lastIndex) {
    re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
    }

enter image description here

DEMO

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103