-
-
Save kensnyder/552566 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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