Here’s an example how you can generate link from given string using regex:

Code of index.html:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./script.js"></script>
<p><strong>Text: </strong>For more info, visit
<p><strong>Generated link: </strong> 
  <span id="generated-link"></span>
    <button onclick="generateLink()">Generate</button>

Code of script.js:

const generateLink = () => {
    let text = "For more info, visit";

    let urlRegex = /(https?:\/\/[^\s]+)/g;

    let textWithLink = text.replace(urlRegex, (url) => {
        return '<a href="' + url + '">' + url + '</a>';

    document.getElementById("generated-link").innerHTML = textWithLink;


On click of the generate button, it will execute the generateLink() method of script.js file. Here regex ‘/(https?:\/\/[^\s]+)/g’ detects all urls in a given string and replace function will replace url with anchor tag.

Support On Demand!