How to replace plain URLs with links using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 7, 2024
3 min

banner

# How to replace plain URLs with links using JavaScript

To replace plain URLs with links using JavaScript:

  1. Call the String.replace() method with a regular expression that matches URLs and a replacement string.
  2. The replacement string should use a capturing group to get access to the matched URL.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="container"> <h3>First: https://bobbyhadz.com</h3> <h3>Second: https://google.com</h3> <h3>Third: https://youtube.com</h3> </div> <button id="btn">Replace URLs with Links</button> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the code for the index.js file.

index.js
function replaceUrlsWithLinks(text) { const expressionWithHttp = /(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*))/gi; const regex = new RegExp(expressionWithHttp); return text.replace(regex, "<a href='$1'>$1</a>"); } const container = document.getElementById('container'); const btn = document.getElementById('btn'); btn.addEventListener('click', () => { container.innerHTML = replaceUrlsWithLinks( container.innerHTML, ); });

replace plain urls with links

The code for this article is available on GitHub

The replaceUrlsWithLinks() function takes a string and replaces all occurrences of a URL in the string with an <a> tag with the corresponding URL.

The regular expression in the example matches URLs that start with a protocol ( https:// or http://).

index.js
function replaceUrlsWithLinks(text) { const expressionWithHttp = /(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*))/gi; let regex = new RegExp(expressionWithHttp); return text.replace(regex, "<a href='$1'>$1</a>"); } const container = document.getElementById('container'); /** * <h3> * First: <a href='https://bobbyhadz.com'>https://bobbyhadz.com</a> * </h3> * * ... the rest of the URLs */ console.log(replaceUrlsWithLinks(container.innerHTML));
The code for this article is available on GitHub

The String.replace() method returns a new string with one, some, or all matches of a regular expression replaced with the provided replacement.

The method takes the following parameters:

NameDescription
patternThe pattern to look for in the string. Can be a string or a regular expression.
replacementA string used to replace the substring match by the supplied pattern.
The String.replace() method returns a new string with the matches of the pattern replaced. The method doesn't change the original string.

Strings are immutable in JavaScript.

After we construct the regex, we replace each match of a URL with an <a> tag that has its href attribute and its text content set to the link.

The regular expression also matches URLs that specify the www. subdomain.

also replace urls that contain www subdomain

The next part of the code sample adds a click event listener to the button element.

index.js
const btn = document.getElementById('btn'); btn.addEventListener('click', () => { container.innerHTML = replaceUrlsWithLinks( container.innerHTML, ); });
The code for this article is available on GitHub

Every time the button is clicked, the event handler function is invoked.

The function sets the innerHTML property of the container div to the result of calling the replaceUrlsWithLinks() function with the element's inner HTML markup.

The replaceUrlsWithLinks() function returns a string where all plain URLs are replaced by anchor elements with href property and inner text set to the corresponding URL.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.