1

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:

$("#div").html(this.html().substring(0,4));

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

Shaunak D
  • 20,588
  • 10
  • 46
  • 79
user3653087
  • 70
  • 1
  • 8

4 Answers4

10

Use a callback for the .html(),

$('#div').html(function(i, currentHtml) {
  return currentHtml.substring(0, 4);
});

Demo

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

$("#div").text(function(i, currentText) {
    return currentText.substring(0, 4);
});

Refer :

Slice vs Substring

Turns out substring is relatively faster.

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

Community
  • 1
  • 1
Shaunak D
  • 20,588
  • 10
  • 46
  • 79
2

If the div elements contains any HTML (html elements) then .html() return the it's as a string. Example

Note: (It's completely depend on the inner content of you div)

If you want to truncate the plain text, you should use .text() instead of using .html()

Try this:

$("#div").text(function(){   
    return $(this).text().substring(0,4);
});

Working Fiddle

Ishan Jain
  • 8,063
  • 9
  • 48
  • 75
1

Try this :

$("#div").html(function(){
    return $(this).html().substring(0,4)
    });

It will count space also...If any there.

Like DIV have "test four 3" will give you output "test"

K.K.Agarwal
  • 846
  • 5
  • 10
1

Use slice() for this purpose :

$("#div").text(function(){   
    return $(this).text().slice(0,4);
});
PG1
  • 1,220
  • 2
  • 12
  • 27