将段落中的 Web 链接分离到 JS 数组中

Separate web links from paragraph into a JS array

本文关键字:JS 数组 分离 链接 段落中 Web      更新时间:2023-09-26

我检查了上面的所有答案,看看我的答案是否得到了回答,请不要将其标记为重复

在我正在构建的应用程序中,有一个div

<div class="paragraphlink"> </div>

我允许用户输入任何这样的文本

莱科宁是 http://www.formula1.com 进入《福布斯》杂志名人100强榜单的两位一级方程式车手之一,另一位是费尔南多·阿隆索·http://www.google.com。他在《福布斯》杂志的 http://www.forbesmagazine.com 中排名第36位

如果您注意到上述段落中存在网址,您能否帮助我使用JavaScript代码从上述段落中提取所有URL?

你可以正则表达式对象

var reg = new RegExp(/http(s)?:'/'/[a-z0-9_-'.'/]+/ig);
var html = "Räikkönen was among the two Formula One drivers http://www.formula1.com who made it into the Forbes magazine's The Celebrity 100 list, the other being Fernando Alonso http://www.google.com. He is 36th on Forbes magazine's http://www.forbesmagazine.com"
html.match(reg);

将返回一个 URL 数组。

您可以在文本上使用匹配函数来提取网址,例如:

var str = "Räikkönen was among the two Formula One drivers http://www.formula1.com who made it into the Forbes magazine's The Celebrity 100 list, the other being Fernando Alonso http://www.google.com. He is 36th on Forbes magazine's http://www.forbesmagazine.com";
var urls = str.match(/http(s)?:'/'/[a-z0-9_-'.'/]+/ig);
// now the var "urls" is in array with your URL
但是正则表达式

在这里很简单,您可以在许多网站上找到更好的正则表达式。

使用正则表达式

像这样的正则表达式

     /(http|https|ftp|ftps)':'/'/[a-zA-Z0-9'-'.]+'.[a-zA-Z]{2,3}('/'S*)?/g

将匹配网址

有关Javascript正则表达式的更多信息,请检查此和此