Skip to content

Instantly share code, notes, and snippets.

@adammcarth
Created January 15, 2015 10:47
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 adammcarth/4bdce2a13b4d780dcffd to your computer and use it in GitHub Desktop.
Save adammcarth/4bdce2a13b4d780dcffd to your computer and use it in GitHub Desktop.
function truncate(string, words) {
var max_chars = 6 * parseInt(words);
var words_array = string.split(" ");
var index = parseInt(words) - 1;
var truncated = words_array.slice(0, index).join(" ");
if ( truncated.length > max_chars ) {
truncated = string.slice(0, max_chars) + "...";
} else if ( truncated === string ) {
truncated = string;
} else {
truncated = truncated + "...";
}
return truncated;
}
truncate("I enjoy playing counter strike source.", 3);
// => I enjoy playing...
truncate("I enjoy playing counter strike source.", 6);
// => I enjoy playing counter strike sourc...
truncate("I enjoy playing counter strike source.", 100);
// => I enjoy playing counter strike source.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment