Skip to content

Instantly share code, notes, and snippets.

@58bits
Created June 3, 2015 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 58bits/8b6280a959dc20a45979 to your computer and use it in GitHub Desktop.
Save 58bits/8b6280a959dc20a45979 to your computer and use it in GitHub Desktop.
Truncate String Helper for Handlebars and Node.js
'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_);
};
@58bits
Copy link
Author

58bits commented Jun 3, 2015

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 ...'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment