匹配string中的所有URL并在JavaScript中返回数组 [英] Match all URLs in string and return in array in JavaScript

查看:142
本文介绍了匹配string中的所有URL并在JavaScript中返回数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有以下字符串:

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/';

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

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现在,我只能匹配一个URL,但我想匹配所有。这就是我所拥有的:

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

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

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

任何想法?

推荐答案

在Regexp中传递g

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/

这篇关于匹配string中的所有URL并在JavaScript中返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆