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.
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.
Share Improve this question edited Jun 16, 2014 at 17:17 Shaunak D 20.6k10 gold badges47 silver badges79 bronze badges asked Jun 13, 2014 at 8:02 user3653087user3653087 701 silver badge8 bronze badges4 Answers
Reset to default 10Use 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
If the div elements contains any HTML (html elements) then .html()
return the it's as a string. Example
Note: (It's pletely 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
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"
Use slice() for this purpose :
$("#div").text(function(){
return $(this).text().slice(0,4);
});