Need Help With Javascript Development?

Work with our skilled Javascript developers to accelerate your project and boost its performance.

Hire JavaScript Developers

Support On Demand!

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

Code of index.html:

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

Code of script.js:

const generateLink = () => {
    let text = "For more info, visit https://www.bacancytechnology.com";

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

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

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

Explanation:

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.

Related Q&A