• Post category:JavaScript
  • Reading time:4 mins read

Today we will show you how to detect URLs in text and create a link in JavaScript. When you are working with a messaging application where you may 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 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.codepremix.com and contact us on https://www.codepremix.com/contact to share your queries.")
// Output: ["www.codepremix.com", "https://www.codepremix.com/contact"]

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.codepremix.com and contact us on https://www.codepremix.com/contact to share your queries.")
// Output: Visit <a href="http://www.codepremix.com" target="_blank" rel="noopener noreferrer">www.codepremix.com</a> and contact us on <a href="https://www.codepremix.com/contact" target="_blank" rel="noopener noreferrer">https://www.codepremix.com/contact</a> to share your queries.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!!

Leave a Reply