In this tutorial, we will see how we can detect URLs in a text and create a link for the same using JavaScript. We have often seen in chat applications that whenever we type a URL and send that to someone, the application automatically converts the text to link. Let’s see how that’s done.
This task will be done in two parts :
- Detect URLs in a text
- Convert the text to hyperlink
Table of Contents
Detect URLs in a Text
We will use regex (regular expression) to accomplish this task. We will also use the match method along with regex to get the desired output. In this output we’ll get a list on URLs present in the text.
Let’s see an example with Code:
function detectURLs(message) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
return message.match(urlRegex)
}
detectURLs("Visit www.codingiseasy.com and contact us on https://codingiseasy.com/contact-us/ to share your queries.")
Output:
// Output: ["www.codingiseasy.com", "https://codingiseasy.com/contact-us/"]
Converting URL in Text to Hyperlinks:
In the next step, we will make a clickable link instead of the URLs as a text. 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.
Code:
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>'
});
}
Using that function you can create a hyperlink for any URL. Hope you understood the process of converting URLs to hyperlink using JS.