有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:

if (string.length > 25) {
  string = string.substring(0, 24) + "...";
}

当前回答

注意,这只需要在Firefox中执行。

所有其他浏览器都支持CSS解决方案(参见支持表):

p {
    white-space: nowrap;
    width: 100%;                   /* IE6 needs any width */
    overflow: hidden;              /* "overflow" value must be different from  visible"*/ 
    -o-text-overflow: ellipsis;    /* Opera < 11*/
    text-overflow:    ellipsis;    /* IE, Safari (WebKit), Opera >= 11, FF > 6 */
}

具有讽刺意味的是,我从Mozilla MDC获得了该代码片段。

其他回答

聪明的地方:D

//My Huge Huge String let tooHugeToHandle = `It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).` //Trim Max Length const maxValue = 50 // The barber. const TrimMyString = (string, maxLength, start = 0) => { //Note - `start` is if I want to start after some point of the string if (string.length > maxLength) { let trimmedString = string.substr(start, maxLength) return ( trimmedString.substr( start, Math.min(trimmedString.length, trimmedString.lastIndexOf(' ')) ) + ' ...' ) } return string } console.log(TrimMyString(tooHugeToHandle, maxValue))

也许我错过了一个例子,有人在处理空值,但3 TOP答案不适合我,当我有空值(当然,我意识到错误处理是和百万其他事情不是回答这个问题的人的责任,但由于我已经使用了一个现有的函数以及一个优秀的截断省略答案,我想我将为其他人提供它。

如。

javascript:

news.comments

使用截断函数

news.comments.trunc(20, true);

然而,在news.comments为空时,这将“中断”

最后

checkNull(news.comments).trunc(20, true) 

trunc函数由KooiInc提供

String.prototype.trunc =
 function (n, useWordBoundary) {
     console.log(this);
     var isTooLong = this.length > n,
         s_ = isTooLong ? this.substr(0, n - 1) : this;
     s_ = (useWordBoundary && isTooLong) ? s_.substr(0, s_.lastIndexOf(' ')) : s_;
     return isTooLong ? s_ + '&hellip;' : s_;
 };

我简单的空检查器(检查文字“空”的东西 (这捕获未定义,"",null, "null",等等。)

  function checkNull(val) {
      if (val) {
          if (val === "null") {
              return "";
          } else {
              return val;
          }
      } else {
          return "";
      }
  }

大多数现代Javascript框架(JQuery, Prototype等)都有一个附加在String上的实用函数来处理这个问题。

下面是Prototype中的一个例子:

'Some random text'.truncate(10);
// -> 'Some ra...'

这似乎是您希望其他人处理/维护的功能之一。我会让框架来处理它,而不是编写更多的代码。

最好的函数。归功于文本省略。

function textEllipsis(str, maxLength, { side = "end", ellipsis = "..." } = {}) {
  if (str.length > maxLength) {
    switch (side) {
      case "start":
        return ellipsis + str.slice(-(maxLength - ellipsis.length));
      case "end":
      default:
        return str.slice(0, maxLength - ellipsis.length) + ellipsis;
    }
  }
  return str;
}

例子:

var short = textEllipsis('a very long text', 10);
console.log(short);
// "a very ..."

var short = textEllipsis('a very long text', 10, { side: 'start' });
console.log(short);
// "...ng text"

var short = textEllipsis('a very long text', 10, { textEllipsis: ' END' });
console.log(short);
// "a very END"

本质上,检查给定字符串的长度。如果它比给定的长度n长,剪辑到长度n (substr或slice),并添加html实体&hellip;(…)到剪短的字符串。

这样的方法看起来像

function truncate(str, n){
  return (str.length > n) ? str.slice(0, n-1) + '&hellip;' : str;
};

如果你所说的“更复杂”是指在字符串的最后一个单词边界处截断,那么你需要额外的检查。 首先将字符串剪辑到所需的长度,然后将其结果剪辑到最后一个单词边界

function truncate( str, n, useWordBoundary ){
  if (str.length <= n) { return str; }
  const subString = str.slice(0, n-1); // the original check
  return (useWordBoundary 
    ? subString.slice(0, subString.lastIndexOf(" ")) 
    : subString) + "&hellip;";
};

您可以用您的函数扩展本机String原型。在这种情况下,str形参应该被删除,函数中的str应该被替换为:

String.prototype.truncate = String.prototype.truncate || 
function ( n, useWordBoundary ){
  if (this.length <= n) { return this; }
  const subString = this.slice(0, n-1); // the original check
  return (useWordBoundary 
    ? subString.slice(0, subString.lastIndexOf(" ")) 
    : subString) + "&hellip;";
};

更教条的开发人员可能会因此强烈地责备你(“不要修改你不拥有的对象”)。不过我不介意)。

一种不扩展String原型的方法是创建 您自己的helper对象,包含您提供的(长)字符串 和前面提到的截断方法。这就是代码片段 下面。

const LongstringHelper = str => { const sliceBoundary = str => str.substr(0, str.lastIndexOf(" ")); const truncate = (n, useWordBoundary) => str.length <= n ? str : `${ useWordBoundary ? sliceBoundary(str.slice(0, n - 1)) : str.slice(0, n - 1)}&hellip;`; return { full: str, truncate }; }; const longStr = LongstringHelper(`Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum`); const plain = document.querySelector("#resultTruncatedPlain"); const lastWord = document.querySelector("#resultTruncatedBoundary"); plain.innerHTML = longStr.truncate(+plain.dataset.truncateat, !!+plain.dataset.onword); lastWord.innerHTML = longStr.truncate(+lastWord.dataset.truncateat, !!+lastWord.dataset.onword); document.querySelector("#resultFull").innerHTML = longStr.full; body { font: normal 12px/15px verdana, arial; } p { width: 450px; } #resultTruncatedPlain:before { content: 'Truncated (plain) n='attr(data-truncateat)': '; color: green; } #resultTruncatedBoundary:before { content: 'Truncated (last whole word) n='attr(data-truncateat)': '; color: green; } #resultFull:before { content: 'Full: '; color: green; } <p id="resultTruncatedPlain" data-truncateat="120" data-onword="0"></p> <p id="resultTruncatedBoundary" data-truncateat="120" data-onword="1"></p> <p id="resultFull"></p>

最后,您可以使用css仅截断HTML节点中的长字符串。它给你较少的控制,但可能是可行的解决方案。

body { font: normal 12px/15px verdana, arial; margin: 2rem; } .truncate { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; width: 30vw; } .truncate:before{ content: attr(data-longstring); } .truncate:hover::before { content: attr(data-longstring); width: auto; height: auto; overflow: initial; text-overflow: initial; white-space: initial; background-color: white; display: inline-block; } <div class="truncate" data-longstring="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."></div>