Skip to content

Instantly share code, notes, and snippets.

@naeluh
Forked from pbojinov/trim.string.js
Created October 16, 2015 17:44
Show Gist options
  • Save naeluh/af270eb0d801968851d9 to your computer and use it in GitHub Desktop.
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.
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