const regex = /(?:^|\ |\n)(((?:(?:http(?:s)?\:)?(?:\/\/))|(?:\/\/))?(?:(?=[a-z0-9\-\.]{1,255}(?=\/|\ |$|\:|\n|\?|\,|\!))(?:(?:(?:[a-z0-9]{1}(?:[a-z0-9\-]{1,62})?\.){1,127})[a-z]{2,}(?:\.[a-z]{2})?))(?:[a-z0-9\/\-\_\%\?\&\!\$\'\,\(\)\*\.\+\=\;])*?)(?=$|\.(?=\ |$)|\:|\n|\ |\?(?=\ |$)|\,|\!)/ig;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?:^|\\ |\\n)(((?:(?:http(?:s)?\\:)?(?:\\\/\\\/))|(?:\\\/\\\/))?(?:(?=[a-z0-9\\-\\.]{1,255}(?=\\\/|\\ |$|\\:|\\n|\\?|\\,|\\!))(?:(?:(?:[a-z0-9]{1}(?:[a-z0-9\\-]{1,62})?\\.){1,127})[a-z]{2,}(?:\\.[a-z]{2})?))(?:[a-z0-9\\\/\\-\\_\\%\\?\\&\\!\\$\\\'\\,\\(\\)\\*\\.\\+\\=\\;])*?)(?=$|\\.(?=\\ |$)|\\:|\\n|\\ |\\?(?=\\ |$)|\\,|\\!)', 'ig')
const str = `I really like to go to google.com and google stuff.
<br>
I also like http://hercdev.io, both are pretty cool!
http://google.com
<br>
This is the url to an image: https://objects.dreamhost.com/herc-scripts/chicken_sombrero.gif
<br>
But this is the actual image: <img src="https://objects.dreamhost.com/herc-scripts/chicken_sombrero.gif" style="max-width: 100px;" />
<br>
Note that the url to the image in the <img> tag is unaffected. This is true for things that are already links also, like <a href="http://google.com" target="_blank">this.</a>`;
const subst = `<a href="$1">$1</a>`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions