Paul
Paul

Reputation: 419

Add target="_blank" to link with JavaScript

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?

Upvotes: 15

Views: 32602

Answers (5)

Toni Bianchetti
Toni Bianchetti

Reputation: 51

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 :-)

Upvotes: 2

maerics
maerics

Reputation: 156642

Fraught with problems but usable with plain JavaScript:

function addBlankTargets(s) {
  return (""+s).replace(/<a\s+href=/gi, '<a target="_blank" href=');
}

Or with jQuery:

function addBlankTargets(s) {
  var p = $('<p>' + s + '</p>');
  p.find('a').attr('target', '_blank');
  return p.html();
}
var s = '<a href="www.google.com">Google</a> and '
      + '<a href="www.yahoo.com">Yahoo</a> '
      + 'are search engines.';
var x = addBlankTargets(s);
x; // => '<a href="www.google.com" target="_blank">Google</a> and
   //     <a href="www.yahoo.com" target="_blank">Yahoo</a>
   //     are search engines.'

Upvotes: 10

iLevi
iLevi

Reputation: 936

in two lines

var links = document.getElementsByTagName('a');
for(i in links)
    links[i].target=="_blank"?links[i].style.color="#f0f" : links[i].style.color ='#0f0'

jsfiddle

Upvotes: 0

timw4mail
timw4mail

Reputation: 1776

Not very difficult with plain js.

var links = document.getElementsByTagName('a');
var len = links.length;

for(var i=0; i<len; i++)
{
   links[i].target = "_blank";
}

Upvotes: 28

hayesgm
hayesgm

Reputation: 9096

You can use jQuery to parse the element, add the attribute, and then read out the HTML, like so:

 var addTarget = function(input) {
   return $('<span>' + input + '</span>').find('a').attr('target', '_blank').html();
 };

 console.log(addTarget('<a href="www.google.com">Google</a>'));

Upvotes: 0

Related Questions