最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery: Cut off div text after 4 characters - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

4 Answers 4

Reset to default 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

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);
});
发布评论

评论列表(0)

  1. 暂无评论