Вот набор функций, которые я использовал для форматирования текста:
/**
* Adds anchor elements to all the links inside a string
* @param {string} text text to be converted
* @returns {string} converted text
*/
function setLinks(text) {
var regex = /(https?:[/]{0,2}|[w]{3}[.])[^ "'>]{1,}/g;
text = text.replace(/</g, "<");
text = text.replace(/>/g, ">");
return text.replace(regex, addLink);
}
/**
* Surrounds string in an anchor tag
* @param {string} link url of link
* @returns {string}
*/
function addLink(link) {
var descr = String(link).replace(/^(https?:[/]{0,2})?([w]{3}[.])?/, "www.");
if (!/^https?:[/]{2}/.test(link)) link = `http://${link}`;
return `<a href=${link} target="_blank">${descr}</a>`;
}
document.write(setLinks('Foo https://example1.com bar foo https://www.example2.com bar https://example3.com/url'));