在任意字符串中的所有URL中创建链接

时间:2012-08-28 20:55:15

标签: javascript regex

  

可能重复:
  How to replace plain URLs with links?

我希望通过解析文本输入(通过javascript)来查找所有URL,然后链接它们(换行标记),以便用户只需单击它们,从而使用户的生活更轻松。 Facebook甚至SO都做了类似的事情,让你知道我在寻找什么。

function censorLinks(text) {
    return text.replace(
        new RegExp('(https?://[^\\s]+)', 'g'),
        '<a href="$1" target="_blank">$1</a>'
    );
}

我不需要支持每个协议。我认为现在可以找到http和https。我假设http://以外的所有内容都是一个URL。这几乎有效,但有一个小问题:如果URL以句点the period gets included结尾。我想这是一个有效的URL,但我认为在我的情况下这不太可能。我该如何预防这段时间?

1 个答案:

答案 0 :(得分:1)

就像@Truth所说,这可能是一个重复的帖子,但是......

我最近做了类似的事情,没有对此进行测试,但也许这会让我感到震惊......

    var email = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
    var url = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

    function convert(input) {
        return input
            .replace(url,'<a href="$1" target="blank">$1</a>')
            .replace(email, '<a href="mailto:$1">$1</a>');
    }

编辑:修正错误