0

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.

Cinder
  • 319
  • 2
  • 15
  • You can use regular expressions for it. Check here https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url – tagir Oct 24 '20 at 07:28

1 Answers1

1

You need to do a replacement of the url string inside the corresponding area.

area.replace(anchor, createAnchorTag(anchor))
Rajoe
  • 111
  • 4