Skip to content

Instantly share code, notes, and snippets.

@efeminella
Created March 14, 2012 04:57
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save efeminella/2034192 to your computer and use it in GitHub Desktop.
Save efeminella/2034192 to your computer and use it in GitHub Desktop.
Plain text URL to anchor tags Handlebars Helper
// 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 );
});
}());
// 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