Do you want to be a good Web Developer?

Enter Your Email To Get Our Exclusive Tutorials
And Offer Right In Your Email

Join TalkersCode Community And Recieve Exclusive Tutorials
On Web Development Right Via Email.

Convert URL Text Into Clickable HTML Links Using JavaScript.

Sunday, Jan 8, 2017

Tags:- JavaScript HTML


In This tutorial we will Convert the URL text into a HTML clickable links using JavaScript.For eg; When you post comments in tutorials and your comment contains some link of a website many times the link is post in a simple text format not in a clickable HTML link format and due to this other users will ignore your link.So in this tutorial we will solve this problem.You may also like create short url using PHP.


See Demo
Convert Text into HTML URL


Make a HTML file and define markup and script To Convert URL into HTML Links

We have to make a HTML file and named it url.html

<html>
<head>
  <script type="text/javascript">
    function convert()
    {
	  var text=document.getElementById("url").value;
	  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	  var text1=text.replace(exp, "<a href='$1'>$1</a>");
	  var exp2 =/(^|[^\/])(www\.[\S]+(\b|$))/gim;
	  document.getElementById("converted_url").innerHTML=text1.replace(exp2, '$1<a target="_blank" href="http://$2">$2</a>');
    }
  </script>
</head>

<body>
  
  <h1>Convert URL Text Into Clickable HTML Link Using JavaScript</h1>
  <textarea id="url" Placeholder="Enter Some Text With Links">
  </textarea>
  <input type="button" value="Convert" onclick="convert();">
  <p id="converted_url"></p>

</body>
</html>

in This step we create a textarea where user will write some text with links and after that when the user clicks on convert button we call convert(); function.In this function we write two regular expressions to detect link with in a text.You may also like extract url data like facebook using PHP and ajax.


First regular expression detects whether the link starts from http,https,ftp,file and if yes then it convert the text to Clickable HTML link


Second regular expression is used to detect whether the link starts from www and if yes then it convert the text to Clickable HTML link and insert the text into paragraph.


You may also like create short urls using PHP and google api. Thats all, this is how to Convert URL Text Into Clickable HTML Links Using JavaScript.You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

Join Us With Our 21000+ Subscribers And Get Our Latest Tutorials Update Via Email