Skip to content

Instantly share code, notes, and snippets.

@namnm
Created January 15, 2016 04:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save namnm/4385f44bb58906ea2995 to your computer and use it in GitHub Desktop.
Save namnm/4385f44bb58906ea2995 to your computer and use it in GitHub Desktop.
js truncate method for string without cutting word
String.prototype.trunc = function(n) {
if (this.length <= n) {
return this;
}
var truncated = this.substr(0, n);
if (this.charAt(n) === ' ') {
return truncated;
}
return truncated.substr(0, truncated.lastIndexOf(' '));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment