Limit text length with jQuery

Asked

Viewed 5,090 times

3

inserir a descrição da imagem aqui

I have a function that places the famous 3 dots ... after x characters. But I am in doubt of how to make the reticence enter exactly at the end of the word where is the limit of characters. Follow the code I’m using:

$(function(){
    $(".limit").each(function(i){
        len=$(this).text().length;
        if(len>60)
        {
            $(this).text($(this).text().substr(0,80)+'...');
        }
    });       
});
  • I suggest that when the person hovers the mouse over, open a box with the full caption. In that case you could solve the problem do something interesting, could create a small overflow-auto, with a bearing on the right with a similar cool facebook style...

3 answers

6

I don’t know if you need this necessarily in javascript, because this can be solved in css in a very simple way.

You can use the property:

text-overflow: ellipsis;

Here is the example of implementation:

http://jsfiddle.net/Y5vpb/

Obs: Now using less javascript your page gets faster.

  • in this case that you passed the line does not go down, I updated the question with the picture of the problem, I think we can have a better

4

Without having a more detailed description of the problem I leave a suggestion:

$(function () {
    $(".limit").each(function (i) {
        var texto = $(this).text();
        var len = texto.length;
        var novoTexto = [];
        var novoLength = 0;
        if (len > 60) {
            texto.split(' ').each(function (str) { // partir a frase em pedacos  e iterar
                novoLength += str.length; // ir contando o tamanho
                if (novoLength < 80) novoTexto.push(str);
            });
            novoTexto = novoTexto.join(' ') + '...'; // juntar de novo e adicionar "..."
            $(this).text(novoTexto);
        }
    });
});
  • Well I basically have a DIV(limit) where the size is fixed and the surplus comes out only what I want instead of cutting EX: a mer... I want to cut EX: a ...- I tested what passed me but unsuccessfully

  • 1

    Sergio, it would be safer to split by \b? I’m not sure, but I believe it would solve more cases than break in the spaces.

  • \b? how would that be?

0

I took a bit of a leap of faith in our friend, I think it might help other people.

$(function(){
   $(".limit").each(function (i) {
       var text = $(this).text();
       var len = text.length;
       if (len > 80) {
           var query = text.split(" ", 10);
           query.push('...');
           res = query.join(' ');
           $(this).text(res);
       }
    });
});

Here is an example:

http://jsfiddle.net/sz1sLrud/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.