Created
January 16, 2019 15:52
-
-
Save avitorio/4645f2333eb2b8f0f51825243b7661b9 to your computer and use it in GitHub Desktop.
Truncate string without cutting words in Javascript.
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
// 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