4

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?

Marcolac
  • 901
  • 4
  • 14
  • 27

2 Answers2

9

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.

Community
  • 1
  • 1
Zorayr
  • 23,770
  • 8
  • 136
  • 129
6

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.

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
  • Thank you it works perfectly for urls beginning with http. How could I make it works for links beginning with www? – Marcolac Jan 15 '13 at 08:38
  • @Marcolac see my update, otherwise choose a more accurate regular expression for link detection – Fabrizio Calderan Jan 15 '13 at 08:42
  • Ok, I meant how to replace both www and http://. But I guess I just have to add both functions. Thank you very much for your help. – Marcolac Jan 15 '13 at 08:44