Clue Mediator

Find URLs in string and make a link using JavaScript

📅September 19, 2020

Today we will show you how to find URLs in string and make a link using JavaScript. Recently I was developing a messaging application where we need to detect the URL from the chat message string and create a clickable HTML link instead of that text. So I am going to share the JavaScript function with you.

Split this example in two different parts

  1. Detect URLs from the string
  2. Replace a hyperlink instead of the text URLs

1. Detect URLs from the string

Here, we’ll use the match method of the string along with the regular-expression" target="_blank" class="tag-link">regular expression to detect the URLs in text. This method will provide us the list of the URLs in the array.

function detectURLs(message) {
  var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
  return message.match(urlRegex)
}

detectURLs("Visit www.cluemediator.com and subscribe us on https://www.cluemediator.com/subscribe for regular updates.")
// Output: ["www.cluemediator.com", "https://www.cluemediator.com/subscribe"]

2. Replace a hyperlink instead of the text URLs

In the next step, we will create a clickable link instead of the URLs. Here, we will use the replace method of the string and that method will be used to create a HTML `a` tag in the text.

function replaceURLs(message) {
  if(!message) return;

  var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
  return message.replace(urlRegex, function (url) {
    var hyperlink = url;
    if (!hyperlink.match('^https?:\/\/')) {
      hyperlink = 'http://' + hyperlink;
    }
    return '<a href="' + hyperlink + '" target="_blank" rel="noopener noreferrer">' + url + '</a>'
  });
}

replaceURLs("Visit www.cluemediator.com and subscribe us on https://www.cluemediator.com/subscribe for regular updates.")
// Output: Visit <a href="http://www.cluemediator.com" target="_blank" rel="noopener noreferrer">www.cluemediator.com</a> and subscribe us on <a href="https://www.cluemediator.com/subscribe" target="_blank" rel="noopener noreferrer">https://www.cluemediator.com/subscribe</a> for regular updates.

That’s it for today.
Thank you for reading. Happy Coding..!!