-
-
Save naeluh/af270eb0d801968851d9 to your computer and use it in GitHub Desktop.
Shorten string to specified max length and and append ... at the end. It will not cut in the middle of a word but at the minimum amount of words under the limit.
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
function trim(message, maxLength) { | |
var m = message; | |
var maxLen = maxLength; | |
//string is too long, lets trim it and append ... | |
if (m.length > maxLen) { | |
var lastSpace = m.lastIndexOf(' '); | |
//there is no space in the word | |
if (lastSpace === -1) { | |
m = m.slice(0, maxLen-3); | |
m += '...'; | |
} | |
else if (lastSpace > -1) { | |
m = m.slice(0, maxLen-3); | |
var t = m.lastIndexOf(' '); | |
m = m.slice(0, t); | |
m += '...'; | |
} | |
} | |
return m; | |
} | |
var message = "You may be starting to notice a trend from my recent articles here on HTML5Hub."; | |
message = trim(message, 40); //"You may be starting to notice a trend..." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment