How to trim content of element and put “…” if the characters go over a certain limit?

后端 未结 3 758
甜味超标
甜味超标 2021-01-05 19:04

I would like to trim a part of the if it is too long. This will make sure the table doesn\'t get messed up. All the data in the following table is re

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-05 19:21

    Here's a function that will respect word boundaries (it won't split a word in half).

    var maxLength = 30;
    
    $('.shorten').each(function() {
        var text = $(this).text();
    
        if (text.length > maxLength) {
            var output =/^.{0,30}(?=[\.,; ])\b/.exec(text)[0]
            $(this).text(output + "...");
        }     
    });
    

提交回复
热议问题