How to convert url (websites,email) from a string to html <a> tags with javascript

Quick implementation

If you want convert text url into clickable links quickly (within the dom or a string), you need to know that this is not an easy job to do for your own. The URI'S are complex and there are million of cases where your self-implemented function could fail. For example :

function linkify(inputText) {
    var replacedText, replacePattern1, replacePattern2, replacePattern3;

    //URLs starting with http://, https://, or ftp://
    replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
    replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');

    //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
    replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
    replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');

    //Change email addresses to mailto:: links.
    replacePattern3 = /(([a-zA-Z0-9\-\_\.])[email protected][a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
    replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

    return replacedText;

The previous function would work but, there's a better way to achieve this task.

Use a library (Linkify.js)

Well, the first point is clean and functional, but in some cases it can fail. Instead of give you headaches learning how to process a string and search for url's, we recommend you to use a library that will handle all this job for you.

We are talking about Linkify.js. Linkify is a JavaScript plugin for finding links in plain-text and converting them to HTML <a> tags. It works with all valid web URLs and email addresses. To include linkify in your project visit the homepage and download a distribution (or use npm or bower) and include the scripts in your document :

<!-- Linkify Core -->
<script src="linkify.min.js"></script>

<!-- If you want to use the jquery module include this script -->
<script src="linkify-jquery.min.js"></script>

Linkify offers more than 1 way of initialization, with jQuery you can convert directly DOM content in links, for example :

<div id="linkDemo">
  Visit , it has a lot of interesting content. You can contact us writing to [email protected]


Should output :

Visit , it has a lot of interesting content. You can contact us writing to [email protected]

Or use only the linkify core without jQuery (read more about modes here):

<div id="linkDemo"></div>

  var str = '<p>For help with, please email [email protected]</p>';
  var processedContent = linkifyStr(str, options);
  // or
  // var processedContent = str.linkify();

  document.getElementById("linkDemo").innerHTML = processedContent;  

You can test your own text in the official homepage here, have fun !

This could interest you

Become a more social person