-
-
Save dandean/552319 to your computer and use it in GitHub Desktop.
This file contains hidden or 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(length) { | |
return this | |
.slice(0, length + 1) | |
.split(/\s+/) | |
.slice(0, -1) | |
.join(" "); | |
}; | |
// Examples | |
// The "v" marks the first character out of bounds. | |
// v | |
"cut that shit out now!".truncateToWord(15); // "cut that shit" | |
// v | |
"cut that shit out now!".truncateToWord(13); // "cut that shit" | |
// v | |
"cut that shit out now!".truncateToWord(10); // "cut that" |
This file contains hidden or 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
// From @tr0gd0rr (Ken Snyder) | |
// Untested | |
String.prototype.truncateToWord = function(length) { | |
return this.match(new RegExp('^(.{0,'+(+length)+'})(\\b|$)'))[1] | |
.replace(/\s+$/,''); // ghetto quick-fix to remove trailing white space | |
}; | |
// Examples | |
// The "v" marks the first character out of bounds. | |
// v | |
"cut that shit out now!".truncateToWord(15); // "cut that shit" | |
// v | |
"cut that shit out now!".truncateToWord(13); // "cut that shit" | |
// v | |
"cut that shit out now!".truncateToWord(10); // "cut that" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment