Limit length of text with jQuery

2

Ihaveafunctionthatputsthefamous3dots...afterxcharacters.ButIamindoubthowtomakethereticencesenterexactlyattheendofthewordwherethelimitofcharacters.HereisthecodeI'musing:

$(function(){$(".limit").each(function(i){
        len=$(this).text().length;
        if(len>60)
        {
            $(this).text($(this).text().substr(0,80)+'...');
        }
    });       
});
    
asked by anonymous 14.03.2015 / 00:03

3 answers

5

I do not know if you need this necessarily in javascript, as this can be solved in css in a very simple way.

You can use the property:

text-overflow: ellipsis;

Here is the implementation example:

link

Obs: Now using less javascript your page gets faster.

    
14.03.2015 / 06:00
4

Without 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);
        }
    });
});
    
14.03.2015 / 00:10
0

I gave a wipe to the function of our friend, I think this can 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:

link

    
16.11.2015 / 14:14