How to convert a URL inside a string to a hyperlink in JavaScript

1 Answer

0 votes
function convertUrlsToLinks(str) {
    return str.replace(/(https?:\/\/[^\s]+)/g, '<a href="$1">$1</a>');
}
 
const str = "This is my website check it out https://www.collectivesolver.com";
const result = convertUrlsToLinks(str);
 
console.log(result);



/*
run:

This is my website check it out <a href="https://www.collectivesolver.com">https://www.collectivesolver.com</a>

*/

 



answered May 2, 2025 by avibootz
edited May 2, 2025 by avibootz
...