Last Updated: February 25, 2016
·
6.96K
· pixeloution

Truncate the text of a jQuery object to a specified length, at the nearest space

I love jQuery - I have nothing against pure javascript, but the birth of the jQuery framework killed a lot of my personal javascript pain points. Here's a problem we recently handled at work where we wanted to truncate text to a given character length, but to walk back to the nearest space so we wouldn't truncate mid-word.

In order to understand the easiest solution, its first important to understand that with jQuery you can pass a function to setter methods and return the value you want set. For example:

$('#myText').text(function() {
    return 'this is my new text'
});

So now all we need to do is write a function that given a string, does the work. Well, that's easy enough:

function maxLength(maxLen)
{
    return function truncateToNearestSpace(idx, text)
    {
        // this may chop in the middle of a word
        var truncated = text.substr(0, maxLen);

        if (/[^\s]$/.test(truncated))
            return truncated.replace(/\s[^\s]+$/, "");
        else
            return truncated.trim();
    }
}

And how do you use it?

// usage
$('.selector').text(maxLength(50));

Any questions? The maxLength function returns a custom truncator function which is built with the maxLen value. The truncateToNearestSpace function first truncates to the exact length of maxLen then it does a little work:

if (/[^\s]$/.test(truncated))

If your regEx skills are weaker, you may not recognize this, but it checks if the last character is not a space. If its not, we replace the last space, and everything after it, and return the result.

The other option is the string, after being truncated, ends in a space, in which case we strip the space off and return it, with .trim() - this method is unsupported in older IE but there is a cheap and easy way to add it for IE:

''.trim||(String.prototype.trim=function(){
    return this.replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g,'')
});

which I found with a quick google search.