Skip to content

Instantly share code, notes, and snippets.

@drewrawitz
Created September 29, 2016 19:53
Show Gist options
  • Save drewrawitz/32010ddeb28f78c49c615a8fa139896c to your computer and use it in GitHub Desktop.
Save drewrawitz/32010ddeb28f78c49c615a8fa139896c to your computer and use it in GitHub Desktop.
JS Truncate without cutting off words
var truncate = function(text, characterLimit) {
if( !text || text.length < characterLimit ){ return text; }
var expressionString = "^(.{" + characterLimit + "}[^\\s]*).*";
var expression = new RegExp(expressionString);
var truncatedText = text.replace(expression, "$1");
return truncatedText + '...'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment