12

For example, I have the following string:

var string = 'watch this video http://vimeo.com/8122132 and then see this picture http://www.flickr.com/photos/pmorgan/32606683/';

I wish to find all the valid URLs and place them in an array, done in JavaScript (and jQuery), so in this case:

url[0] = http://vimeo.com/8122132
url[1] = http://www.flickr.com/photos/pmorgan/32606683/

For now, I can only match one URL, but I wish to match all. This is what I have:

geturl = new RegExp("(^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))");
var url = geturl.exec(string);
$('#urls').html(url[0]);

Trust me, putting url[1], url[2], etc. doesn't work :(

Any ideas?

2
  • 1
    Why only support ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal? [\w\-]+ will match every protocol possible. For example, your regexp won't match google-search:foobar. Commented Dec 31, 2009 at 18:00
  • actually, i was only hoping to match urls with oembed support, but the pattern I found has all these protocols, maybe I'll just make it (http|https)... Commented Jan 2, 2010 at 12:50

1 Answer 1

17

Pass "g" in Regexp

geturl = new RegExp(
          "(^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))"
         ,"g"
       );


string.match(geturl).length
2

string.match(geturl)
 http://vimeo.com/8122132, http://www.flickr.com/photos/pmorgan/32606683/
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.