Replace URL in HTML or text content with clickable link using JavaScript

By Faruque Ahamed Mollick

In this tutorial, we are going to see how to select the URL from text or HTML content or from a string from an element and make it clickable using JavaScript. We are going to use jQuery in this tutorial.

Before we go through the JavaScript, first create some paragraph content within a div element. Below you can see that we have created it:

<div id="content">
  <p>This is the content which contains some URL. Here is a URL - https://www.codespeedy.com.</p>
  <p>And this is without HTTPS - www.codespeedy.com which will be detected by the "www" part.</p>
  <p>All the URLs from these contains will be replaced into clickable links by JaVascript.</p>
</div>

You can see three URL in the above HTML code. If you run the above code on your browser, the URL is not clickable links. The browser can not convert URL into a clickable link automatically.

Locate the Geo-position of a visitor in JavaScript



Convert seconds to HH-MM-SS format in JavaScript

Here we are going to replace the URLs from the above HTML code and make them clickable links. To do it we are going to use jQuery. Below is our JavaScript code:

$(document).ready(function(){

   function replace_content(content)
   {
   var exp_match = /(\b(https?|):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
   var element_content=content.replace(exp_match, "<a href='$1'>$1</a>");
   var new_exp_match =/(^|[^\/])(www\.[\S]+(\b|$))/gim;
   var new_content=element_content.replace(new_exp_match, '$1<a target="_blank" href="http://$2">$2</a>');
   return new_content;
   }

   var content = $('#content').html();
   $('#content').html(replace_content(content));

});

In the above code, we have first created a JavaScript function. The function will take the content, text or string as a parameter inside it. All the necessary code is inside the function. The function then returns the content back by replacing the URL into clickable links. We are actually adding the anchor tag to the target URL to that URL that we can see as text.

Retrieve the width of div element in JavaScript

After that, we have set the returned value as the HTML content which replaces the previous content and makes the URLs clickable. Now if we run it on our browser, we can see the paragraph and the all the URL that was not clickable first is now clickable.

 

Leave a Reply

Your email address will not be published. Required fields are marked *