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 acplish that?
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 acplish that?
Share Improve this question edited Jan 15, 2013 at 8:25 Marcolac asked Jan 15, 2013 at 8:17 MarcolacMarcolac 9314 gold badges15 silver badges29 bronze badges 2- Isn't the link clickable by default? – Johan Commented Jan 15, 2013 at 8:19
- 1 should div have a class? <div class="try"></div> stackoverflow./questions/3809401/… – salexch Commented Jan 15, 2013 at 8:22
2 Answers
Reset to default 9You 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.
for every new message inserted in your chat do something like
var conversation = "This message contains a link to http://www.google. "
+ "and another to www.stackoverflow.";
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.">http:
* //www.google.</a>and another to <a href="http://stackoverflow.">
* www.stackoverflow.</a>
*/
then re-append the new message into your chat.