匹配string中的所有URL并在JavaScript中返回数组

时间:2009-12-31 16:49:08

标签: javascript jquery regex

例如,我有以下字符串:

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

我希望找到所有有效的URL并将它们放在一个数组中,用JavaScript(和jQuery)完成,所以在这种情况下:

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

目前,我只能匹配一个网址,但我想匹配所有网址。这就是我所拥有的:

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]);

相信我,把url [1],url [2]等不起作用:(

有什么想法吗?

1 个答案:

答案 0 :(得分:16)

在Regexp中传递“g”

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/