Bacancy Technology
Bacancy Technology represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.
12+
Countries where we have happy customers
1050+
Agile enabled employees
06
World wide offices
12+
Years of Experience
05
Agile Coaches
14
Certified Scrum Masters
1000+
Clients projects
1458
Happy customers
Artificial Intelligence
Machine Learning
Salesforce
Microsoft
SAP
October 17, 2023
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.