-
-
Save chrisl8888/292993756ea3c3ad6ede to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Plain text URL to anchor tags Handlebars Helper | |
(function(){ | |
// defines markup enhancement regex | |
var protocol = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim | |
, scheme = /(^|[^\/])(www\.[\S]+(\b|$))/gim; | |
/* | |
* Registers a Helper method with handlebars which, given a string of | |
* plain text or existing markup, provides enhancements of plain text | |
* URLs, converting them to their respective anchor tag equivilents.= | |
*/ | |
Handlebars.registerHelper('enhance', function(text) { | |
text = text.replace( protocol, '<a href="$1" target="_blank">$1</a>'); | |
text = text.replace( scheme, '$1<a href="http://$2" target="_blank">$2</a>' ); | |
return new Handlebars.SafeString( text ); | |
}); | |
}()); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Plain text URL to anchor tags Handlebars Helper Spec | |
describe( 'Handlebars Helpers', function() { | |
// define a reference to the underlying helpers object. | |
var helpers = Handlebars.helpers | |
, enhance = helpers.enhance; | |
describe( 'The "enhance" markup helper', function() { | |
it ( 'should be registered', function() { | |
expect( enhance ).toBeDefined(); | |
}); | |
it ( 'should return a Handlebars.SafeString', function() { | |
expect( enhance( "some text" ) instanceof Handlebars.SafeString).toBeTruthy(); | |
}); | |
it ( 'should preserve existing markup', function() { | |
var expected = '<strong>Some unescaped markup</strong> and a <a href="#">link</a>'; | |
var actual = enhance( expected ).string; | |
expect( actual ).toEqual( expected ); | |
}); | |
it ( 'should replace URLs with anchor tags', function() { | |
var actual = enhance( 'Some text with a link http://www.ericfeminella.com' ); | |
expect( actual.string ).toEqual( 'Some text with a link <a href="http://www.ericfeminella.com" target="_blank">http://www.ericfeminella.com</a>' ); | |
}); | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment