将段落中的Web链接分隔为JS数组

时间:2012-04-26 15:09:49

标签: javascript jquery

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

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

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

我允许用户输入任何类似的文字

  

莱科宁是两位一级方程式车手 http://www.formula1.com 之一,他们入选福布斯杂志的The Celebrity 100榜单,另一位是Fernando Alonso http:/ /www.google.com 即可。他在“福布斯”杂志的 http://www.forbesmagazine.com

中排名第36位

如果您发现上述段落中有网址。你可以帮我用javascript代码从上面的段中提取所有网址吗?

3 个答案:

答案 0 :(得分:0)

使用正则表达式

像这样的正则表达式

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

将匹配网址

有关Javascript正则表达式检查的更多信息thisthis

答案 1 :(得分:0)

您可以使用文本上的匹配功能来提取网址,例如:

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

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

答案 2 :(得分:0)

您可以使用RegExp对象

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

将返回一组网址。