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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With