查找链接并使其可单击

Mar*_*lac 3 javascript regex jquery

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

            $('#try').prepend(my_message);
Run Code Online (Sandbox Code Playgroud)

有:

            <div id='try'></div>
Run Code Online (Sandbox Code Playgroud)

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

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

关于如何实现这一点的任何想法?

Zor*_*ayr 7

您应该使用正则表达式将所有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>"); 
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,您可以查看如何使用链接替换纯URL?编码恐怖:URL的问题.希望这可以帮助.


fca*_*ran 5

对于插入聊天中的每条新消息,都会执行类似的操作

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>
 */
Run Code Online (Sandbox Code Playgroud)

然后将新消息重新附加到聊天中.