我正在使用下面的函数来匹配给定文本中的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>"); 
}

当前回答

经过几个来源的输入,我现在有一个很好的解决方案。这与编写自己的替换代码有关。

的答案。

小提琴。

function replaceURLWithHTMLLinks(text) {
    var re = /(\(.*?)?\b((?:https?|ftp|file):\/\/[-a-z0-9+&@#\/%?=~_()|!:,.;]*[-a-z0-9+&@#\/%=~_()|])/ig;
    return text.replace(re, function(match, lParens, url) {
        var rParens = '';
        lParens = lParens || '';

        // Try to strip the same number of right parens from url
        // as there are left parens.  Here, lParenCounter must be
        // a RegExp object.  You cannot use a literal
        //     while (/\(/g.exec(lParens)) { ... }
        // because an object is needed to store the lastIndex state.
        var lParenCounter = /\(/g;
        while (lParenCounter.exec(lParens)) {
            var m;
            // We want m[1] to be greedy, unless a period precedes the
            // right parenthesis.  These tests cannot be simplified as
            //     /(.*)(\.?\).*)/.exec(url)
            // because if (.*) is greedy then \.? never gets a chance.
            if (m = /(.*)(\.\).*)/.exec(url) ||
                    /(.*)(\).*)/.exec(url)) {
                url = m[1];
                rParens = m[2] + rParens;
            }
        }
        return lParens + "<a href='" + url + "'>" + url + "</a>" + rParens;
    });
}

其他回答

我对Travis的代码做了一些小的修改(只是为了避免任何不必要的重新声明-但它对我的需求很好,所以做得很好!):

function linkify(inputText) {
    var replacedText, replacePattern1, replacePattern2, replacePattern3;

    //URLs starting with http://, https://, or ftp://
    replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
    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).
    replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
    replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');

    //Change email addresses to mailto:: links.
    replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
    replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

    return replacedText;
}

首先,滚动自己的regexp来解析url是一个糟糕的想法。您必须想象这是一个足够常见的问题,根据rfc,有人已经为它编写、调试和测试了一个库。URI是复杂的——查看Node.js中URL解析的代码和关于URI方案的维基百科页面。

在解析URL时,有大量的边缘情况:国际域名,实际的(.museum)和不存在的(.etc)顶级域名,奇怪的标点符号(包括括号),URL末尾的标点符号,IPV6主机名等。

我已经查看了大量的库,尽管有一些缺点,但还是有一些值得使用:

Soapbox的linkify已经投入了大量精力,2015年6月的一次重大重构删除了jQuery依赖项。它仍然存在idn问题。 AnchorMe是一个自称更快更精简的新产品。还有一些IDN问题。 Autolinker.js列出了非常具体的特性(例如:将正确处理HTML输入。该实用程序不会改变anchor()标签内的href属性”)。当演示版本可用时,我将对其进行一些测试。

我很快就取消了这个任务的库:

Django的urlize不能正确处理某些tld(以下是官方列出的有效tld)。没有演示。 autolink-js不会检测“www.google.com”没有http://,,所以它不太适合自动链接“随意的url”(没有方案/协议)在纯文本中找到。 本·阿尔曼的链接自2009年以来就没有维护过。

如果坚持使用正则表达式,最全面的是Component中的URL regexp,尽管它会错误地检测到一些不存在的双字母tld。

我在谷歌上搜索了最新的消息,发现了这个:

$('p').each(function(){
   $(this).html( $(this).html().replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="$1">$1</a> ') );
});

演示:http://jsfiddle.net/kachibito/hEgvc/1/

工作真的很好,正常的链接。

这样做的最佳脚本: http://benalman.com/projects/javascript-linkify-process-lin/

应该注意关于URI复杂性的警告,但对您的问题的简单回答是: 要替换每个匹配项,你需要在RegEx的末尾添加/g标志: / (\ b (https ? | | ftp文件):\ / \ [-A-Z0-9 +&@#\/%?=~_|!:,.;]*[- A-Z0-9 +&@#\/%=~_|])/ 胃肠道