Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery Get first 100 characters from string, respecting full words [duplicate]

I came across lots of Question regarding this , and i found solution for PHP only. There was no solution on this site for jQuery/javascript way of doing it.

What I want to do is I want to show first 100 characters but I dont want to cut the last word, as it would be meaningless.

Like say this is myself is the last words so it we regularly take substring and y is 100th word, then it would cut it like this is my, which would be meaning less. So I want it like this is..

My original code :

jQuery(".block-text .success-inner-content").each(function(){
    if(jQuery(this).text().length > 100){
        jQuery(this).text(jQuery(this).text().substr(0,98)+'..');
    }
});

here block-text .success-inner-content class is in loop producing list of Divs with text within it.

like image 724
Pratik Avatar asked Dec 04 '25 18:12

Pratik


1 Answers

The lastIndexOf method takes a second parameter that determines where the search starts, so you don't need to cut the string down before finding the last space:

jQuery(".block-text .success-inner-content").each(function () {
  var text = jQuery(this).text();
  if (text.length > 100) {
    jQuery(this).text(text.substr(0, text.lastIndexOf(' ', 97)) + '...');
  }
});

You can also use the text method instead of each to loop the elements and set the text for each:

jQuery(".block-text .success-inner-content").text(function (i, text) {
  return text.length > 100 ? text.substr(0, text.lastIndexOf(' ', 97)) + '...' : text;
});
like image 150
Guffa Avatar answered Dec 06 '25 08:12

Guffa