将"..."添加到长字符串的末尾

sir*_*day -1 string jquery

我在h2标签中有一个文本,我通过以下方式限制其字符数:

$(function() {
  $('h2.questionTitle a').each(function() {
  var $this = $(this);
  $this.text( $this.text().slice(0,80);        
  });
});
Run Code Online (Sandbox Code Playgroud)

但是,我还想修改代码,以便如果字符数被切成80个字符,则在其末尾添加"...".我怎么能这样做?

cdh*_*wie 5

像这样:

$(function() {
  $('h2.questionTitle a').each(function() {
    var $this = $(this);
    var text = $this.text();

    if (text.length > 80) {
      $this.text(text.slice(0, 80) + "...");
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

请注意,在JavaScript中执行此操作可能是错误的方法(除非您正在编写Greasemonkey脚本).输出页面内容时应该执行此类数据突变.