Categories
JavaScript Answers

How to Detect URLs in a JavaScript String and Convert them to Links?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

6 replies on “How to Detect URLs in a JavaScript String and Convert them to Links?”

Looks the same to me?

return <a href="${url}>${url}</a>;

should be:

return <a href="${url}">${url}</a>;

You should remove the double quotes and dollar sign from the href. And the url between the tags should also have the $ removed.

Leave a Reply

Your email address will not be published. Required fields are marked *