2

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.

baao
  • 71,625
  • 17
  • 143
  • 203
Pratik Joshi
  • 11,485
  • 7
  • 41
  • 73

3 Answers3

9

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;
});
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
4

Or you could do it with regex... Something like this -

var s = 'What I want to do is I want to show first 100 characters but I don't want to cut the last word, as it would be meaningless.';

console.log(s.match(/(.{1,19}\w)\s/)[1]+'...');

This matches any 20 characters, ending with a word character, and followed by a space.

Regards

SamWhan
  • 8,296
  • 1
  • 18
  • 45
2

I solved myself. The solution uses substr() and most importantly lastIndexOf() functions of javascript .

jQuery(".block-text .success-inner-content").each(function () {
    if (jQuery(this).text().length > 100) {
        var str =  jQuery(this).text().substr(0,98);
        var wordIndex = str.lastIndexOf(" ");

        jQuery(this).text(str.substr(0, wordIndex) + '..');
    }
});
somethinghere
  • 16,311
  • 2
  • 28
  • 42
Pratik Joshi
  • 11,485
  • 7
  • 41
  • 73