diff --git a/template_helpers.js b/template_helpers.js index 004d133..62ea288 100644 --- a/template_helpers.js +++ b/template_helpers.js @@ -202,7 +202,7 @@ * */ Handlebars.registerHelper("ellipsis", function(text, limit, options) { - if (!text) { return; } + if (!text) { return ""; } // If we get a number, convert it to a string. // We convert things to a string because [object Number] doesn't have the `split` method. @@ -224,8 +224,8 @@ words = text.split(" "); for(var i = 0; i < words.length; i++) { - count += words[i].length + 1; - if(count < limit) { + count += words[i].length + (i < words.length-1 ? 1 : 0); + if(count <= limit) { result.push(words[i]); } } diff --git a/test/ellipsis.js b/test/ellipsis.js index 88fbf1d..399a56e 100644 --- a/test/ellipsis.js +++ b/test/ellipsis.js @@ -1,7 +1,10 @@ describe('Handlebars.helpers.ellipsis', function() { var tests = [ - { text: 'The quick brown fox', len: 12, expected: 'The quick...' } + { text: '', len: 1, expected: '' }, + { text: 'The quick brown fox', len: 12, expected: 'The quick...' }, + { text: 'This is shorter than the limit', len: 42, expected: 'This is shorter than the limit' }, + { text: 'This is as long as the limit', len: 28, expected: 'This is as long as the limit' }, ]; it('should truncate words correctly', function() {