Closed afeld closed 11 years ago
Nooo, don't want to hijack people's regular links... Just want to do this for external links
On Sep 19, 2012, at 12:16 AM, Aidan Feldman notifications@github.com wrote:
If newWindow is true, existing anchor tags should get target="blank" added.
— Reply to this email directly or view it on GitHub.
Sure we do! How about a config option? modifyExisting
or something?
What's the use case? And are you looking to update only links created by Autolinker, or all links that it can get its hands on?
I couldn't see this as being what a user would expect in a generalized sense.. They might have links in a given page that refer to internal urls for their site, but then want to autolink external urls found in the plain text to new windows.
I suppose that makes sense. For Jux, for example, I thinking that if someone forgets to include the target="_blank"
on external links they added manually, they wouldn't want someone to leave their page.
Ah, then you might want a separate method to handle that :)
Try this:
var anchorTagRegex = /<a(?:(?:\s+\w+(?:\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/g,
targetAttrRegex = /target\s*=\s*(".*?"|'.*?'|[^'">\s]+)/;
var makeLinksOpenInNewWindow = function( html ) {
return html.replace( anchorTagRegex, function( anchorTag ) {
var targetAttrMatch = anchorTag.match( targetAttrRegex ); // find any pre-existing 'target' attribute
if( targetAttrMatch ) {
// For the case where the 'target' attr exists, and it is something other
// than "_blank", replace it. We always want it to be "_blank".
var targetAttrValue = targetAttrMatch[ 1 ].replace( /['"]/g, "" ); // strip away any quote characters from the value
if( targetAttrValue !== "_blank" ) {
anchorTag = anchorTag.replace( targetAttrRegex, 'target="_blank"' );
}
} else {
// no target attribute, add it
anchorTag = anchorTag.substr( 0, anchorTag.length - 1 ) + ' target="_blank">';
}
return anchorTag;
} );
}
// Testing... Convert to unit tests :)
var nonTargetStr = 'The <a href="http://www.yahoo.com">quick</a> brown fox';
var targetBlankStr = 'The <a href="http://www.yahoo.com" target="_blank">quick</a> brown fox'; // this one shouldn't change
var targetSomethingElseStr = 'The <a href="http://www.yahoo.com" target="somethingElse">quick</a> brown fox';
var expectedStr = 'The <a href="http://www.yahoo.com" target="_blank">quick</a> brown fox';
console.log( "No target attr test passes: ", makeLinksOpenInNewWindow( nonTargetStr ) === expectedStr );
console.log( "target='_blank' test passes: ", makeLinksOpenInNewWindow( targetBlankStr ) === expectedStr );
console.log( "target='somethingElse' test passes: ", makeLinksOpenInNewWindow( targetSomethingElseStr ) === expectedStr );
Maybe I should make a separate github repo for that little utility... lol
If
newWindow
istrue
, existing anchor tags should gettarget="blank"
added.