user3653087 user3653087 - 1 year ago 69
Javascript Question

JQuery: Cut off div text after 4 characters

I only want to display the first four characters of a div, but it seems to be more difficult than needed and google isn't very helpful. Different variations of this don't seem to work:


I really want to avoid having an extra variable in there that stores the text first.


Use a callback for the .html(),

    return $(this).html().substring(0,4);


$(this).html() and not this.html()

You can also use .text() in this case if the div consists only of plain text.

    return $(this).text().substring(0,4);

Refer :

Slice vs Substring

Turns out substring is relatively faster.

JsPerf test : slice() vs substring() vs others