Skip to content

Instantly share code, notes, and snippets.

@gf3
Created August 11, 2009 20:09
Show Gist options
  • Save gf3/166083 to your computer and use it in GitHub Desktop.
Save gf3/166083 to your computer and use it in GitHub Desktop.
Truncate a string to the closest word
// 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 ↓ marks the first character out of bounds.
// ↓
"cut that shit out now!".truncateToWord( 15 ) // cut that shit
// ↓
"cut that shit out now!".truncateToWord( 13 ) // cut that shit
// ↓
"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