pbojinov
9/12/2013 - 12:34 AM

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 w

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..."