Add target="_blank" to link with JavaScript

Viewed 29197

I need to write a method that takes a String and parses it for links (a href). If it finds a link it should add target="_blank" to the link, if it is not already there.

Example: The Inputstring "

 <a href="www.google.com">Google</a> and <a href="www.yahoo.com"> target="_blank">Yahoo</a> are search engines

... should result in the output String

<a href="www.google.com" target="_blank">Google</a> and <a href="www.yahoo.com" target="_blank">Yahoo</a> are search engines

Any idea how to realize this?

5 Answers

If you are targeting at modern browsers, instead of manipulating a string containing HTML and having to handle all the many special cases, you can transform the string into DOM. At this point manipulating the DOM is trivial and you can then convert it back to a serialised string.

function decorateRichText(html) {
  const domParser = new DOMParser()
  const document = domParser.parseFromString(html, `text/html`)
  const serializer = new XMLSerializer()

  // Handles external links
  const links = document.querySelectorAll(`a`)

  links.forEach((link) => {
    if (link.href) {
      if (isExternalUrl(link.href)) {
        link.target = `_blank`
        link.rel = `noopener noreferrer`
      }
    }
  })

  return serializer.serializeToString(document)
}

Leave the browser JS engine do the heavy stuff and remember: code that you don't write is code you have not to debug :-)

Related