Skip to content

Instantly share code, notes, and snippets.

@kensnyder
Forked from dandean/gist:552319
Created August 27, 2010 01:05
Show Gist options
  • Save kensnyder/552566 to your computer and use it in GitHub Desktop.
Save kensnyder/552566 to your computer and use it in GitHub Desktop.
// Truncate a string to the closest word
String.prototype.truncateToWord = function(len) {
return (len = Number(len)) >= 0 ?
this.match(new RegExp('^([\\s\\S]{0,' + len + '})(:?\\s|$)'))[1] :
undefined;
};
// Examples
// The "v" marks the first character out of bounds.
// v
"A rambunctious child jumps. Does he eat pavement?".truncateToWord(5); // "A"
// v
"A rambunctious child jumps. Does he eat pavement?".truncateToWord("31"); // "A rambunctious child jumps."
"".truncateToWord(10); // ""
"text".truncateToWord(0); // ""
"text".truncateToWord(-1); // undefined
"text".truncateToWord("a"); // undefined
// v
"line1\nline2".truncateToWord(8); // "line1"
// v
"line1\nline2".truncateToWord(14); // "line1\nline2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment