How to cut text inside a div when it reaches a certain number of characters in jQuery?

I know that there are many truncate scripts, but I cannot use most of them because of the cms integration issues I'm working on.

Basically I have to do it like this:

  • get the number of characters inside a div
  • If the amount exceeds a certain amount (say, 10 characters), the text inside the div should be trimmed and added "..." to the end.

Being terrible in javascript, this is my lame non-working attempt:

if ($('div.text').val().length > 10) {

   //     

   ($('div.text').append('...');

}

Can anybody help?

+5
source share
8 answers
if ($('div.text').text().length > 10)

or

if ($('div.text').html().length > 10)

Div elements don't have the value returned by val (), but they have text or html

and then you probably want to truncate the text like

var text = $('div.text').text();
text = text.substr(0,10) + '...';
$('div.text').text(text);
+12

CSS text-overflow: . ( IE7 +), Firefox 7. jQuery.

+7

- :

$('div.text').each(function() {
    var maxchars = 250;
    var seperator = '...';

    if ($(this).text().length > (maxchars - seperator.length)) {
        $(this).text($(this).text().substr(0, maxchars-seperator.length) + seperator);
    }
});

.

+2

.text() :

$('div.text').text(function(i, text) {
    var t = $.trim(text);
    if (t.length > 10) {
        return $.trim(t).substring(0, 10) + "...";
    }
    return t;
});

jsfiddle.

+1

- :

$("div.text").each(function() {
    var $this = $(this);
    var text = $this.text();
    if (text.length > 10) {
        $this.text(text.substr(0, 7) + "...");
    }
}
0
var string_limit = 10;

if ($('div.text').text().length > string_limit )
    $('div.text').text($('div.text').text().substring(0, string_limit -1) + '...');
}

This checks the length limit specified in string_limit. If it is too long, it reduces the text to a limited length (excluding word boundaries, punctuation marks, etc.). Adds an ellipsis and sets the content to the shortened version.

0
source

Thanks for the question and answers. I used this code for multiple captions and it helped me:

$('span.title-cut').each(function() {
        var title = $(this).text();
        if (title.length > 10) {
        title = title.substr(0, 10) + '...';    
        }
        $(this).text(title);
     });
0
source

If you do not want to trim the middle of the word, just follow these steps:

  if ($("div.text").text().length > 10) {
    var ttext = $("div.text").text().substr(0, 10);
    ttext = ttext.substr(0, ttext.lastIndexOf(" "))  + '...';
    $("div.text").text(ttext);
  }
0
source

All Articles