Skip to content

Instantly share code, notes, and snippets.

@avitorio
Created January 16, 2019 15:52
Show Gist options
  • Save avitorio/4645f2333eb2b8f0f51825243b7661b9 to your computer and use it in GitHub Desktop.
Save avitorio/4645f2333eb2b8f0f51825243b7661b9 to your computer and use it in GitHub Desktop.
Truncate string without cutting words in Javascript.
// From @NT3RP on https://stackoverflow.com/questions/5454235/shorten-string-without-cutting-words-in-javascript
var yourString = "The quick brown fox jumps over the lazy dog"; //replace with your string.
var maxLength = 6 // maximum number of characters to extract
//trim the string to the maximum length
var trimmedString = yourString.substr(0, maxLength);
//re-trim if we are in the middle of a word
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment