如何在JavaScript字符串中检测并获取URL

24

如何在 JavaScript 中检测和获取字符串中的 URL?

示例:

var string = "hei dude, check this link http:://google.com and http:://youtube.com"
如何从我的字符串中获得类似这样的结果:
var result = ["http:://google.com", "http:://youtube.com"]

怎么做呢?


对于自然语言文本中的URL,有许多例外情况需要考虑。为什么不使用像这样的库?https://github.com/Andrew-Kang-G/url-knife - Kang Andrew
1
Dupe 不正确,因为 OP 正试图找到类似 URL 的匹配项,但由于在 http 后使用了双重 ::,所以它们并不是格式良好的 URL。 - anubhava
2个回答

54

您的输入在 http 后面有双重冒号::。不确定这是否是故意的。如果确实是,请使用以下内容:

var matches = string.match(/\bhttps?::\/\/\S+/gi);

如果只需要一个冒号:,则使用:

var matches = string.match(/\bhttps?:\/\/\S+/gi);

正则表达式演示


1
100%正确。我也这样做。 - QasimRamzan
var matches = string.match(/\bhttp?:://\S+/gi); console.log(matches)变量匹配 = 字符串.匹配(/\bhttp?:://\S+/gi); 控制台.日志(匹配); - QasimRamzan
3
太好了,@anubhava非常感谢你。 - monoy suronoy
1
似乎它没有检测到:"https://www.youtube.com/watch?v=eogv_ItM9s8" - I am L
1
那并不是那么简单的。你必须考虑许多特殊情况。 - Kang Andrew

6

const string = "hei dude, check this link http:://google.com and http:://youtube.com"
const matches = string.match(/\bhttp?::\/\/\S+/gi);
console.log(matches);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接