I want to find all URLs within a plain text. Then I want to wrap these URLs into an href
to make them clickable.
Basically, I'm struggling with putting the links back. I have this, so far:
Create anchor tag:
function createAnchorTag(anchor) {
html = `<a href="${anchor}" target="about_blank" rel="noopener noreferrer">${anchor}</a>`;
return html;
}
Find all hrefs:
let word = 'https';
let areas = Array.from(document.querySelectorAll('.description'));
areas.forEach(area => {
if (area.innerText.includes('https')) {
let str = area.innerText;
let link = str.split(' ');
for (let i=0; i < link.length; i++) {
if(link[i].includes('https')) {
let anchor = link[i];
createAnchorTag(anchor);
anchor = anchor.replace(anchor, html);
}
}
}
});
}
A text could be something like: "This is my text. Here is a link: https://somelink.com And then there is more text."
How can I replace https://somelink.com in my text?
anchor = anchor.replace(anchor, html);
does not update the link to a clickable replacement. But if I use area += anchor.replace(anchor, html);
instead, it appends a clickable link.