【问题标题】:Match all URLs in string and return in array in JavaScript匹配字符串中的所有 URL 并在 JavaScript 中以数组形式返回
【发布时间】:2009-12-31 16:49:08
【问题描述】:

例如,我有以下字符串:

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/

目前,我只能匹配一个 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]);

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

有什么想法吗?

【问题讨论】:

  • 为什么只支持ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal[\w\-]+ 将匹配所有可能的协议。例如,您的正则表达式与 google-search:foobar 不匹配。
  • 其实,我只是希望将 url 与 oembed 支持匹配,但我发现的模式包含所有这些协议,也许我会做到 (http|https)...

标签: javascript jquery regex


【解决方案1】:

在正则表达式中传递“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/

【讨论】:

    猜你喜欢
    • 2020-08-07
    • 2014-12-21
    • 1970-01-01
    • 2014-05-07
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2016-10-19
    相关资源
    最近更新 更多