JS:在文本中查找URL,建立链接

时间:2013-10-27 23:57:04

标签: javascript angularjs

在JS中重写的以下PHP代码是什么,以便文本blob中的url链接可以用html链接替换?我已经开始了jsfiddle

<?php

// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";

// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {

   // make the urls hyper links
   echo preg_replace($reg_exUrl, "<a href="{$url[0]}">{$url[0]}</a> ", $text);

} else {

   // if no urls in the text just return the text
   echo $text;

}
?>

1 个答案:

答案 0 :(得分:7)

使用此:

var text = "The text you want to filter goes here. http://google.com";
text = text.replace(
    /((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?)/g,
    '<a href="$1">$1</a>'
);

说明:

g这里是一个全球旗帜;它将取代所有网址。

我还为整个表达式添加了一个捕获组,因此我可以使用反向引用$1