最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Match all URLs in string and return in array in JavaScript - Stack Overflow

programmeradmin0浏览0评论

For example, I have the following string:

var string = 'watch this video  and then see this picture /';

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] = 
url[1] = /

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?

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?

Share Improve this question asked Dec 31, 2009 at 16:49 SaminSamin 6503 gold badges11 silver badges23 bronze badges 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. – Eli Grey 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)... – Samin Commented Jan 2, 2010 at 12:50
Add a comment  | 

1 Answer 1

Reset to default 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/
发布评论

评论列表(0)

  1. 暂无评论