Reputation: 271
I have this fiddle https://jsfiddle.net/kz935gge/5/ where you can type text and display it like in a chat view.
I would like to make links recognized if it's possible.
For instance, if you type http://www.google.com , you can see that the link isn't recognized.
function sendMessage()
{
var myDate = new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
var mm = document.getElementById("myMessage").value;
var mainDiv = document.getElementById("mainblock");
var para = document.createElement("p");
var node = document.createTextNode(myDate+"(Me) :"+mm);
para.appendChild(node);
var element = document.createElement('div');
element.appendChild(para);
element.className = 'bubble bubble-alt yellow';
mainDiv.appendChild(element);
}
Any advice on how can I achieve this ?
Thanks
Upvotes: 1
Views: 62
Reputation: 720
Use regex to replace the links:
.replace(/((?:https?:\/\/|www)[^\s]+)/g,"<a href='$1'>$1</a>")
Update made here: https://jsfiddle.net/kz935gge/10/
Answer updated to support https
Wanted to update this answer to draw attention to zzzzBov's comment "this is a very naive regular expression, and fails to properly escape the contents of the link which makes it vulnerable to XSS attacks"
This is expression is just a starting point, more work is required to make it secure.
Upvotes: 2