Skip to content

Instantly share code, notes, and snippets.

@kensnyder

kensnyder/gist:552566

Forked from dandean/gist:552319
Created Aug 27, 2010
Embed
What would you like to do?
// 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