匹配字符串中的所有url并返回JavaScript中的数组

时间:2021-04-16 20:18:55

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并将它们放在一个数组中,用JavaScript(和jQuery)完成,所以在这种情况下:

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:

目前,我只能匹配一个URL,但我希望匹配所有URL。这就是我所拥有的:

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 :(

相信我,输入url[1]、url[2]等都不行:(

Any ideas?

什么好主意吗?

1 个解决方案

#1


16  

Pass "g" in Regexp

通过“g”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/

#1


16  

Pass "g" in Regexp

通过“g”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/