【问题标题】:Find links and make them clickable查找链接并使其可点击
【发布时间】:2013-01-15 08:17:22
【问题描述】:

我正在开发一个与 socketio 的聊天。每次发送消息时,我都会使用这个非常简单的 jquery 来显示它:

            $('#try').prepend(my_message);

与:

            <div id='try'></div>

我想做的是查找发布的消息是否包含链接,如果包含链接,则使其可点击。我需要找到 http:// 和 www。

我发现了几个相关的问题,但没有一个给出我正在寻找的解决方案。

有什么办法可以做到这一点吗?

【问题讨论】:

标签: javascript jquery regex


【解决方案1】:

您应该使用正则表达式将所有 http/https 链接替换为锚标记:

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"<a href='$1'>$1</a>"); 
}

有关更多信息,您可以查看How to replace plain URLs with links?Coding Horror: The Problem with URLs。希望这会有所帮助。

【讨论】:

    【解决方案2】:

    对于您聊天中插入的每条新消息,请执行以下操作

    var conversation = "This message contains a link to http://www.google.com "
                     + "and another to www.stackoverflow.com";
    
    conversation = conversation.replace(/(www\..+?)(\s|$)/g, function(text, link) {
       return '<a href="http://'+ link +'">'+ link +'</a>';
    })
    
    
    
    /**
     *  output :
     *  This message contains a link to <a href="http://www.google.com">http:
     *  //www.google.com</a>and another to <a href="http://stackoverflow.com">   
     *  www.stackoverflow.com</a>
     */
    

    然后将新消息重新附加到您的聊天中。

    【讨论】:

    • 谢谢它非常适合以 http 开头的网址。我怎样才能使它适用于以 www 开头的链接?
    • @Marcolac 查看我的更新,否则选择更准确的正则表达式进行链接检测
    • 好的,我的意思是如何同时替换 www 和 http://。但我想我只需要添加这两个功能。非常感谢您的帮助。
    猜你喜欢
    • 2016-08-07
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多