1

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

DeseaseSparta
  • 271
  • 2
  • 4
  • 12

1 Answers1

2

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.

tempcke
  • 700
  • 8
  • 15
  • Here is a good place to test and also get a detailed explanation of what this regex string is doing: https://regex101.com/r/cB8cQ8/1 – tempcke Jun 09 '15 at 14:24
  • 1
    this is a very naive regular expression, and fails to properly escape the contents of the link which makes it vulnerable to XSS attacks. – zzzzBov Jun 09 '15 at 14:26