Jquery limit characters

I am wondering if it is possible to limit the number of characters in an element with a specified class using jQuery?

For example, the following abbreviated class elements will only show 40 characters.

<p class="shortened">This would be the text limited to 40 Characters</p>

Thanks in advance for your help.

+3
source share
2 answers

Perhaps a plugin?

http://plugins.jquery.com/project/TrimText

Depending on your needs, this can be easy or difficult. Truncating plain text is easy, trimming html is a little more complicated, and if you want to trim html and you have an extension button to return the text, it's even harder.

+4
source

For elements, <input type="text" />you can simply use the attribute maxlength.

, <textarea>, onkeyup .

$('.shortened')
    .keyup(function(e){
        var $this = $(this);
        $this.text($this.text().substring(0, max)); //Set max to 40, or whatever you want
    });

, , , .

$('.shortened')
    .each(function(){ 
        var remainTxt = $(this).text().substring(max, $(this).text().length);
        $(this).text($(this).text().substring(0,max));
    });

: Mark, .text() , "expand".

+6

Source: https://habr.com/ru/post/1752117/


All Articles