Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find links and make them clickable

I'm developing a chat with socketio. Each time a message is sent, I display it using this very simple jquery:

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

with:

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

What I would like to do is to find if the message posted contains a link and if so make it clickable. I need to find either http:// and www.

I found several question related, but none of them gave me the solution I'm looking for.

Any idea on how I can accomplish that?

like image 563
Marcolac Avatar asked Oct 28 '25 01:10

Marcolac


2 Answers

You should use a regex expression to replace all http/https links to anchor tags:

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>"); 
}

For more information you can take a look at How to replace plain URLs with links? and Coding Horror: The Problem with URLs. Hope this helps.

like image 111
Zorayr Avatar answered Oct 29 '25 17:10

Zorayr


for every new message inserted in your chat do something like

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>
 */

then re-append the new message into your chat.

like image 36
Fabrizio Calderan Avatar answered Oct 29 '25 17:10

Fabrizio Calderan