【问题标题】:I want to truncate a text or line with ellipsis using JavaScript [closed]我想使用 JavaScript 用省略号截断文本或行 [关闭]
【发布时间】:2011-06-09 16:06:00
【问题描述】:

我正在寻找一个可以用省略号 (...) 截断字符串的简单脚本

我想将'this is a very long string' 之类的内容截断为'this is a ve...'

我不想使用 CSS 或 PHP。

【问题讨论】:

标签: javascript string truncate


【解决方案1】:
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;

【讨论】:

  • 这 (string.substr(0,5)+'...';) 为我工作。
  • 如果您想取悦排版员,您可以使用,这是一个省略号的专用字形,其中点之间的空间有点窄。
【解决方案2】:

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 获得了全部功劳。

【讨论】:

  • 简洁很好。我用它作为:function truncateWithEllipses(text, max) {return text.substr(0,max-1)+(text.length>max?'…':''); }
  • 我喜欢@AlienLifeForm 上面评论中的解决方案非常优雅
  • 这是一个很好的单行,但它会截断字符串,即使它的长度不超过限制。我会添加一个条件(ES6 示例):export const characterLimit = (text, limit) => text.length > limit ? (text.substr(0, limit - 1).trim() + '...') : text;
  • ES6 函数结束参数:truncateWithEllipses = (text, max, ending = '…') => text.length > max ? text.substr(0, max - ending.length) + ending : text;
  • @KévinBerthommier 如果您还提供了ending 参数,则可能不应该称为truncateWithEllipses,因为您可以更改ending 是什么,然后它不再是WithEllipses .
【解决方案3】:

这会将它限制在您希望它限制的任意多行并且是响应式的

一个没有人建议的想法,根据元素的高度来做,然后从那里剥离它。

小提琴 - https://jsfiddle.net/hutber/u5mtLznf/

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

'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(' ') + '...';
  }
});

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
}

【讨论】:

  • 没有比这更好的了!干得好
【解决方案4】:

类似:

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

【讨论】:

  • 这不是一个完整的解决方案。您需要检查字符串是否实际上大于您要截断的数量。如果为 false,则不应出现 ...。仅仅使用line.substring(0, max_char) 是不够的。
【解决方案5】:

用于防止单词中间或标点符号后面的点。

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

【讨论】:

  • 我喜欢您的解决方案,但您的函数在没有 return text.substring(0, limit) + '...'; 的情况下存在错误。我编辑了您的答案,并将该行添加到您的代码中 + 其他一些微小更改。没有那条线,parseText("1234567 890",5) 返回undefined 但现在效果很好。
【解决方案6】:

这会将省略号放在直线的中心:

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

不完美,但功能齐全。原谅过度评论......对于菜鸟。

【讨论】:

【解决方案7】:

最简单灵活的方式: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,'...')  );

【讨论】:

    【解决方案8】:
    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"
    

    【讨论】:

      【解决方案9】:

      试试这个

      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

      【讨论】:

        【解决方案10】:

        带有 JavaScript 的 HTML:

        <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.

        【讨论】:

          【解决方案11】:

          如果您想将字符串剪切为指定长度并添加点,请使用

          // Length to cut
          var lengthToCut = 20;
          
          // Sample text
          var text = "The quick brown fox jumps over the lazy dog";
          
          // We are getting 50 letters (0-50) from sample text
          var cutted = text.substr(0, lengthToCut );
          document.write(cutted+"...");
          

          或者,如果您不想按长度而是按字数来切割:

          // Number of words to cut
          var wordsToCut = 3;
          
          // Sample text
          var text = "The quick brown fox jumps over the lazy dog";
          
          // We are splitting sample text in array of words
          var wordsArray = text.split(" ");
          
          // This will keep our generated text
          var cutted = "";
          for(i = 0; i < wordsToCut; i++)
           cutted += wordsArray[i] + " "; // Add to cutted word with space
          
          document.write(cutted+"...");
          

          祝你好运……

          【讨论】:

          • 这会为所有字符串添加省略号,即使它们没有被剪切...
          猜你喜欢
          • 2011-09-17
          • 2016-10-18
          • 1970-01-01
          • 2013-11-08
          • 1970-01-01
          • 2011-05-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多