Add target="_blank" to link with JavaScript
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.'
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 :-)
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";
}