Search code examples
jquerycharacter-limit

Loop through h1 elements and output only first 140 characters with ellipsis appended


I want to loop through a set of html elements, in this case H1s, count the characters, and if the character count is greater than 140, I want to truncate the characters and output only the first 140 characters, followed by an elipsis. I have been testing my code through the console, and so far have come up with this.

$( "h1.evTitle" ).each(function( truncate ) {
     console.log($(this).text().substring(0, 140).split(" ").slice(0, -1).join(" ") + "...");
});

This works okay, but it adds the elipsis onto every string, regardless of the length. Any thoughts on what an if statement would look like to only apply this to strings with length greater than 140 characters? Keep in mind, this would be a series of H1s, not just one of them.

Here is my final code, in case anyone wants to do this also.

$('h1').each(function () {
    if ($(this).text().length>140) {
        $(this).text($(this).text().substring(0, 140).split(" ").slice(0, -1).join(" ") + "...");
    }
});

I added in .split(" ") to separate the string into an array containing each word, then I used .slice(0, -1) to remove the last item in the array (so that I could remove any junk characters from partial words, and then used .join(" ") to make that array back into a string again.


Solution

  • $('h1').each(function () {
        if ($(this).text().length>140) {
            $(this).text($(this).text().substr(0, 140) + "...");
        }
    });
    

    jsFiddle example