Skip to content

Instantly share code, notes, and snippets.

@pbojinov
Last active December 5, 2018 16:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save pbojinov/6531779 to your computer and use it in GitHub Desktop.
Save pbojinov/6531779 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.
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