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?
You can use the target="_blank" attribute if you want your users to click on a link that opens up a new browser tab. The target="_blank" attribute is used inside the opening anchor tag like this.
target attributes in JavaScript When a user clicks on a link, the HTML target attribute specifies in which the linked document shall open. The linked document shall open in a new tab if target=" blank" is specified with the anchor element; else, it will do so in the existing tab.
To change the target of a link in HTML, use the target attribute of the <a>… </a> tag. The target attribute can be used to open any link in a new tab, or the same tab, etc.
Description. _blank. Opens the linked document in a new window or tab. _self. Opens the linked document in the same frame as it was clicked (this is default)
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";
}
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With