Use a Regex to Find URLs in a String
We can create our own function that uses a regex to find URLs.
For instance, we can write:
const urlify = (text) => {
const urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, (url) => {
return `<a href="${url}">${url}</a>`;
})
}
const text = 'Find me at http://www.example.com and also at http://stackoverflow.com';
const html = urlify(text);
console.log(html)
We create the urlify functioon that takes a text string.
In the function, we refine the urlRegex variable that has the regex for matching URLs.
We check for http or https .
And we look for slashes and text after that.
The g flag at the end of the regex lets us search for all URLs in the string.
Then we call text.replace with the urlRegex and return a string with the matched url in the callback.
Therefore, when we call urlify with text , we get:
'Find me at <a href="http://www.example.com>http://www.example.com</a> and also at <a href="http://stackoverflow.com">http://stackoverflow.com</a>'
as a result.
We can make the URL search more precise with a more complex regex.
For instance, we can write:
const urlify = (text) => {
const urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(urlRegex, (url) => {
return `<a href="${url}>${url}</a>`;
})
}
const text = 'Find me at http://www.example.com and also at http://stackoverflow.com';
const html = urlify(text);
console.log(html)
We search for http , https , ftp , and file URLs.
And we also include : , letters, ampersands, and underscores in the pattern.