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.
6 replies on “How to Detect URLs in a JavaScript String and Convert them to Links?”
There is an error in your final code block. You’ve left out the terminating ” after the url in the href attribute.
Thanks for this!
Thanks. I fixed the error.
Looks the same to me?
return
<a href="${url}>${url}</a>
;should be:
return
<a href="${url}">${url}</a>
;Sorry, forgot to click save. Now the typo is fixed.
Hello! Late to the party. Have an issue witch using your code when trying to produce an within React <Modal.Body>. It always displays [object Object] when I return url
But when I return
<a href="${url}">${url}</a>
I get the string version if you know what I mean. Not sure how to return urlify() when called like this:
const newText = message.split(‘\n’).map(str =>
{urlify(str)}
);
You should remove the double quotes and dollar sign from the href. And the url between the tags should also have the $ removed.