我正在使用下面的函数来匹配给定文本中的url,并将它们替换为HTML链接。正则表达式工作得很好,但目前我只替换了第一个匹配。
我怎么能替换所有的URL?我想我应该使用exec命令,但我真的不知道如何做到这一点。
function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
return text.replace(exp,"<a href='$1'>$1</a>");
}
识别URL很棘手,因为它们经常被标点符号包围,而且用户经常不使用URL的完整形式。有很多JavaScript函数可以用超链接替换url,但我在基于python的web框架Django中找不到一个像urlize过滤器一样好用的。因此,我将Django的urlize函数移植到JavaScript:
https://github.com/ljosa/urlize.js
一个例子:
urlize('Go to SO (stackoverflow.com) and ask. <grin>',
{nofollow: true, autoescape: true})
=> "Go to SO (<a href="http://stackoverflow.com" rel="nofollow">stackoverflow.com</a>) and ask. <grin>"
第二个参数如果为真,则会插入rel="nofollow"。如果第三个参数为真,则转义HTML中具有特殊含义的字符。请参阅README文件。
谢谢,这对我很有帮助。我还希望能够链接看起来像URL的东西——作为基本需求,它将链接类似www.yahoo.com的东西,即使没有http://协议前缀。所以基本上,如果“www.”存在,它就会链接它,并假设它是http://.我还想让电子邮件变成mailto:链接。示例:www.yahoo.com将被转换为www.yahoo.com
下面是我最终得到的代码(结合了这个页面的代码和我在网上找到的其他东西,以及我自己做的其他东西):
function Linkify(inputText) {
//URLs starting with http://, https://, or ftp://
var replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
var replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
//URLs starting with www. (without // before it, or it'd re-link the ones done above)
var replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
var replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
//Change email addresses to mailto:: links
var replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
var replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
return replacedText
}
在第二次替换中,(^|[^/])部分只替换www.whatever.com,如果它还没有前缀//——以避免重复链接,如果一个URL已经在第一次替换中被链接。此外,www.whatever.com可能位于字符串的开头,这是正则表达式中该部分的第一个“或”条件。
这可以集成为一个jQuery插件,如Jesse P上面所示——但我特别想要一个常规的函数,它不作用于现有的DOM元素,因为我把我有文本,然后添加到DOM,我希望文本是“链接”之前,我添加它,所以我通过这个函数传递文本。伟大的工作。