Question

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.

Was it helpful?

Solution 2

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

jsFiddle example

OTHER TIPS

Just check first:

var str = $(this).text();
if (str.length > 140) {
    str = str.substring(0, 140) + "...";
}

Since you're using jQuery, you might throw a $.trim or two in there:

var str = $.trim($(this).text());
if (str.length > 140) {
    str = $.trim(str.substring(0, 140)) + "...";
}

The first one removes leading and trailing whitespace on the original, the second keeps the ellipsis from being preceded by a space.

Also note that there's a much simpler way to truncate and add an ellipsis (shown above).

If your goal with the split/join was to remove extraneous spaces, I don't think it does, but this will:

var str = $.trim($(this).text());
str = str.replace(/  +/g, " ");
if (str.length > 140) {
    str = $.trim(str.substring(0, 140)) + "...";
}

Live Example | Source (in the example, I write the result back to the element)

Just check if $(this).text().length > 140 before you add the elipsis.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top