使用JavaScript截断文本并添加省略号

101
如何截断字符串并添加省略号(...)?
我想将类似于 'this is a very long string' 的内容截断为 'this is a ve...'。

5
您的意思是截断类似于“这是一个非常长的字符串”的内容,使其变为“这是一...”等等吗? - El Ronnoco
你能提供一个例子吗?"TEXT"是什么意思? - jzd
@jzd 请查看这张截图 http://i964.photobucket.com/albums/ae123/DollarFriend/well.png - Dollar Friend
可能是使用JavaScript缩短长字符串的聪明方法的重复问题。 - Artiom
11个回答

201
function truncate(input) {
   if (input.length > 5) {
      return input.substring(0, 5) + '...';
   }
   return input;
};

或者在ES6中

const truncate = (input) => input.length > 5 ? `${input.substring(0, 5)}...` : input;

5
这个代码(string.substr(0,5)+'...';)对我有用。 - syam
5
如果你想讨好印刷排版人员,可以使用 这个专门用于省略号的字符,其中点之间的空格会稍微变窄。 - st_phan

45

KooiInc对此有很好的回答。总结一下:

String.prototype.trunc = 
      function(n){
          return this.substr(0,n-1)+(this.length>n?'…':'');
      };

现在你可以做:

var s = 'not very long';
s.trunc(25); //=> not very long
s.trunc(5); //=> not...

如果您喜欢将其作为函数,可以参考@AlienLifeForm的评论:

function truncateWithEllipses(text, max) 
{
    return text.substr(0,max-1)+(text.length>max?'…':''); 
}

此处完全归功于KooiInc


6
简明扼要是美好的。我将其用作:function truncateWithEllipses(text, max) {return text.substr(0,max-1)+(text.length>max?'…':''); }。该函数可以截取文本并在末尾加上省略号,以使其长度不超过指定的最大值。 - Alien Life Form
我很喜欢上面@AlienLifeForm的解决方案,非常优雅。 - user2709153
这是一个不错的一行代码,但即使字符串长度没有超过限制,它也会截断字符串。我会添加一个条件(ES6示例):export const characterLimit = (text, limit) => text.length > limit ? (text.substr(0, limit - 1).trim() + '...') : text; - Anton
1
ES6带有结尾参数的函数: truncateWithEllipses = (text, max, ending = '…') => text.length > max ? text.substr(0, max - ending.length) + ending : text; - Kévin Berthommier
2
@KévinBerthommier 如果你还提供了一个 ending 参数,那么可能不应该称其为 truncateWithEllipses,因为你可以更改 ending 是什么,然后它就不再是 WithEllipses 了。 - Joshua Pinter
不会直接向原型添加功能。 - Kevin.a

17

这将限制它显示为你想要的行数,并且具有响应式的特性。

一个没有人提出的想法是,根据元素的高度来进行限制,然后再进行适当的调整。

Fiddle - https://jsfiddle.net/hutber/u5mtLznf/ <- ES6 版本

但基本上你想要获取元素的行高,循环遍历所有的文本,并在达到一定行高时停止:

'use strict';

var linesElement = 3; //it will truncate at 3 lines.
var truncateElement = document.getElementById('truncateme');
var truncateText = truncateElement.textContent;

var getLineHeight = function getLineHeight(element) {
  var lineHeight = window.getComputedStyle(truncateElement)['line-height'];
  if (lineHeight === 'normal') {
    // sucky chrome
    return 1.16 * parseFloat(window.getComputedStyle(truncateElement)['font-size']);
  } else {
    return parseFloat(lineHeight);
  }
};

linesElement.addEventListener('change', function () {
  truncateElement.innerHTML = truncateText;
  var truncateTextParts = truncateText.split(' ');
  var lineHeight = getLineHeight(truncateElement);
  var lines = parseInt(linesElement.value);

  while (lines * lineHeight < truncateElement.clientHeight) {
    console.log(truncateTextParts.length, lines * lineHeight, truncateElement.clientHeight);
    truncateTextParts.pop();
    truncateElement.innerHTML = truncateTextParts.join(' ') + '...';
  }
});

ES6
const linesElement=document.getElementById('lines');
const truncateElement=document.getElementById('truncateme');
const truncateText=truncateElement.textContent;


const getLineHeight = function(element) {
  const lineHeight = window.getComputedStyle(truncateElement)['line-height'];
  if (lineHeight === 'normal') {
    // fuck chrome
    return 1.16 * parseFloat(window.getComputedStyle(truncateElement)['font-size']);
  } else {
    return parseFloat(lineHeight);
  }
}

linesElement.addEventListener('change', () => {
  truncateElement.innerHTML=truncateText
  const truncateTextParts= truncateText.split(' ');
  const lineHeight = getLineHeight(truncateElement);
  const lines = parseInt(linesElement.value);
  
  while(lines * lineHeight < truncateElement.clientHeight) {
    console.log(truncateTextParts.length, lines * lineHeight , truncateElement.clientHeight)
    truncateTextParts.pop();
    truncateElement.innerHTML = truncateTextParts.join(' ') + '...';
  }
})

CSS
#truncateme {
   width: auto; This will be completely dynamic to the height of the element, its just restricted by how many lines you want it to clip to
}

11

类似于:

var line = "foo bar lol";
line.substring(0, 5) + '...' // gives "foo b..."

13
这并不是一个完整的解决方案。您需要检查字符串是否实际上比您要截断的字符数更大。如果是假的,则“...”不应出现。仅使用“line.substring(0, max_char)”将不足以解决问题。 - user1952811
因简洁而获得赞同。楼主未指定门槛要求。 - vhs

9

这将把省略号放在行的中心:

function truncate( str, max, sep ) {

    // Default to 10 characters
    max = max || 10;

    var len = str.length;
    if(len > max){

        // Default to elipsis
        sep = sep || "...";

        var seplen = sep.length;

        // If seperator is larger than character limit,
        // well then we don't want to just show the seperator,
        // so just show right hand side of the string.
        if(seplen > max) {
            return str.substr(len - max);
        }

        // Half the difference between max and string length.
        // Multiply negative because small minus big.
        // Must account for length of separator too.
        var n = -0.5 * (max - len - seplen);

        // This gives us the centerline.
        var center = len/2;

        var front = str.substr(0, center - n);
        var back = str.substr(len - center + n); // without second arg, will automatically go to end of line.

        return front + sep + back;

    }

    return str;
}

console.log( truncate("123456789abcde") ); // 123...bcde (using built-in defaults) 
console.log( truncate("123456789abcde", 8) ); // 12...cde (max of 8 characters) 
console.log( truncate("123456789abcde", 12, "_") ); // 12345_9abcde (customize the separator) 

例如:

1234567890 --> 1234...8910

并且:

A really long string --> A real...string

虽不完美,但功能正常。为了新手能够理解,注释有些多,请谅解。


1
一些类似的函数:https://dev59.com/l3RA5IYBdhLWcg3wyA_1#30613599 - bob

8
为了防止单词中间或标点符号后出现点号,可以采取以下措施。

let parseText = function(text, limit){
  if (text.length > limit){
      for (let i = limit; i > 0; i--){
          if(text.charAt(i) === ' ' && (text.charAt(i-1) != ','||text.charAt(i-1) != '.'||text.charAt(i-1) != ';')) {
              return text.substring(0, i) + '...';
          }
      }
       return text.substring(0, limit) + '...';
  }
  else
      return text;
};
    
    
console.log(parseText("1234567 890",5))  // >> 12345...
console.log(parseText("1234567 890",8))  // >> 1234567...
console.log(parseText("1234567 890",15)) // >> 1234567 890


1
我喜欢你的解决方案,但是你的函数有一个bug,缺少return text.substring(0, limit) + '...';这一行代码。我编辑了你的答案并在你的代码中添加了那行代码和一些其他微小的变化。如果没有那行代码,parseText("1234567 890",5)会返回undefined,但现在它运行得很好。 - Ramin Bateni

5

最简单和灵活的方式:JSnippet DEMO

函数样式:

function truncString(str, max, add){
   add = add || '...';
   return (typeof str === 'string' && str.length > max ? str.substring(0,max)+add : str);
};

原型:

String.prototype.truncString = function(max, add){
   add = add || '...';
   return (this.length > max ? this.substring(0,max)+add : this);
};

使用方法:

str = "testing with some string see console output";

//By prototype:
console.log(  str.truncString(15,'...')  );

//By function call:
console.log(  truncString(str,15,'...')  );

2
function truncate(string, length, delimiter) {
   delimiter = delimiter || "&hellip;";
   return string.length > length ? string.substr(0, length) + delimiter : string;
};

var long = "Very long text here and here",
    short = "Short";

truncate(long, 10); // -> "Very long ..."
truncate(long, 10, ">>"); // -> "Very long >>"
truncate(short, 10); // -> "Short"

2

试试这个

function shorten(text, maxLength, delimiter, overflow) {
  delimiter = delimiter || "&hellip;";
  overflow = overflow || false;
  var ret = text;
  if (ret.length > maxLength) {
    var breakpoint = overflow ? maxLength + ret.substr(maxLength).indexOf(" ") : ret.substr(0, maxLength).lastIndexOf(" ");
    ret = ret.substr(0, breakpoint) + delimiter;
  }
  return ret;
}

$(document).ready(function() {
  var $editedText = $("#edited_text");
  var text = $editedText.text();
  $editedText.text(shorten(text, 33, "...", false));
});

在 Codepen 上查看一个可用的示例:http://codepen.io/Izaias/pen/QbBwwE


0

HTML与JavaScript:

<p id="myid">My long long looooong text cut cut cut cut cut</p>

<script type="text/javascript">
var myid=document.getElementById('myid');
myid.innerHTML=myid.innerHTML.substring(0,10)+'...';
</script>

结果将会是:

My long lo...

祝好

G.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接