Created
June 3, 2015 17:48
-
-
Save 58bits/8b6280a959dc20a45979 to your computer and use it in GitHub Desktop.
Truncate String Helper for Handlebars and Node.js
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
'use strict'; | |
var Handlebars = require('handlebars'); | |
module.exports = function truncate(str, len, words) { | |
var safe = Handlebars.Utils.escapeExpression(str); | |
var tooLong = safe.length > len; | |
var s_ = tooLong ? safe.substr(0, len) : safe; | |
if (words && tooLong) { | |
var index = s_.lastIndexOf(' '); | |
if (index !== -1) { | |
s_ = s_.substr(0, index); | |
} | |
} | |
return new Handlebars.SafeString(tooLong ? s_ + ' …' : s_); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A truncate string Handlebars helper for Node.js (I'm using this in Hapi.js). Will optionally truncate on the last word.
truncate('all the king's horses', 16, true
)=> 'all the king's ...'