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

StackOverflow https://stackoverflow.com/questions/15413852

  •  23-03-2022
  •  | 
  •  

سؤال

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.

هل كانت مفيدة؟

المحلول 2

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

jsFiddle example

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top