-5

Is there a way in pure Javascript to turn links in an HTML document into clickable links? I do not want to use regex to solve this problem.

Let's say I have this list in an HTML5 doc:

<pre>
http://www.test.com
http://www.example.com
http://nicelink.com
</pre>

And I want it to automatically turn into this when the page is loaded:

<pre>
<a href="http://www.test.com">http://www.test.com</a>
<a href="http://www.example.com">http://www.example.com</a>
<a href="http://nicelink.com">http://nicelink.com</a>
</pre>

What would the vanilla JS code look like if I put a script in the header? Something looping through the HTML code and replacing the lines I suppose but I cannot write it in JS.

Signy

Vesa
  • 197
  • 1
  • 7

1 Answers1

1

A way to do this:

var str = $('pre').html().trim();
var ar = str.split('\n');
var html = "";
for(var i=0;i<ar.length;i++)
{
    html +="<a href='"+ar[i]+"'>"+ar[i]+"</a><br>";
}
console.log(html);
$('body').html(html);

DEMO

Manwal
  • 23,450
  • 12
  • 63
  • 93
  • Looking pretty good. Is this really the ultimate answer? Does it cover all the cases? I understand that URIs can be complex in their syntax. – Vesa Aug 20 '14 at 13:11