使用javascript缩短长字符串的聪明方法

时间:2009-07-29 10:44:46

标签: javascript string

有没有人有一个更复杂的解决方案/库来缩短JavaScript的字符串,而不是显而易见的:

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

25 个答案:

答案 0 :(得分:292)

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

现在你可以做到:

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

如果'更复杂',你的意思是截断字符串的最后一个单词边界,那么这可能是你想要的:

String.prototype.trunc =
     function( n, useWordBoundary ){
         if (this.length <= n) { return this; }
         var subString = this.substr(0, n-1);
         return (useWordBoundary 
            ? subString.substr(0, subString.lastIndexOf(' ')) 
            : subString) + "&hellip;";
      };

现在你可以这样做:

s.trunc(11,true) // => not very...

如果您不想扩展本机对象,可以使用:

function truncate( n, useWordBoundary ){
    if (this.length <= n) { return this; }
    var subString = this.substr(0, n-1);
    return (useWordBoundary 
       ? subString.substr(0, subString.lastIndexOf(' ')) 
       : subString) + "&hellip;";
};
// usage
truncate.apply(s, [11, true]); // => not very...

答案 1 :(得分:52)

请注意,这只需要在Firefox上完成。

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

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获得了该代码片段。

答案 2 :(得分:15)

使用lodash's truncate

_.truncate('hi-diddly-ho there, neighborino');
// → 'hi-diddly-ho there, neighbo…'

underscore.string's truncate

_('Hello world').truncate(5); => 'Hello...'

答案 3 :(得分:11)

人们可能希望在JavaScript而不是CSS中执行此操作。

在JavaScript中截断为8个字符(包括省略号):

short = long.replace(/(.{7})..+/, "$1&hellip;");

short = long.replace(/(.{7})..+/, "$1…");

答案 4 :(得分:7)

这是我的解决方案,与其他建议相比有一些改进:

String.prototype.truncate = function(){
    var re = this.match(/^.{0,25}[\S]*/);
    var l = re[0].length;
    var re = re[0].replace(/\s$/,'');
    if(l < this.length)
        re = re + "&hellip;";
    return re;
}

// "This is a short string".truncate();
"This is a short string"

// "Thisstringismuchlongerthan25characters".truncate();
"Thisstringismuchlongerthan25characters"

// "This string is much longer than 25 characters and has spaces".truncate();
"This string is much longer&hellip;"

有:

  • 25岁后第一个空格截断 字符
  • 扩展JavaScript String对象, 所以它可以用于(和链接) 任何字符串。
  • 如果截断,将修剪字符串 导致尾随空间;
  • 将添加unicode hellip实体 (省略号)如果截断的字符串超过25个字符

答案 5 :(得分:4)

大多数现代Javascript框架(JQueryPrototypeetc ...)都有一个实用程序函数,用于处理此问题的String。

这是原型中的一个例子:

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

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

答案 6 :(得分:4)

All modern browsers现在支持一个简单的CSS解决方案,用于在文本行超出可用宽度时自动添加省略号:

p {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

(请注意,这需要以某种方式限制元素的宽度才能产生任何效果。)

基于https://css-tricks.com/snippets/css/truncate-string-with-ellipsis/

应该注意,此方法基于字符数确实限制。如果您需要允许多行文本,它也可以

答案 7 :(得分:3)

我发现的最佳功能。归功于 text-ellipsis

Map<Integer, Integer> rankingById = new HashMap<>();
Queue<Integer> idsByRanking = new PriorityQueue<>(
        Comparator.comparing(rankingById::get).reversed());

void addItem(Item item) {
    Integer id = item.getId();
    idsByRanking.remove(id);
    rankingById.merge(id, item.getRanking(), Integer::sum);
    idsByRanking.add(id);
}

<强>实施例

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;
}

答案 8 :(得分:2)

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

e.g。

javascript:

news.comments

使用截断功能

news.comments.trunc(20, true);

然而,在news.com上 null ,这将“破解”

最终

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

截断功能由 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”的东西 (这会捕获undefined,“”,null,“null”等。)

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

答案 9 :(得分:2)

有时文件名会被编号,索引可能位于开头或结尾。所以我想缩短字符串的中心:

function stringTruncateFromCenter(str, maxLength) {
    const midChar = "…";      // character to insert into the center of the result
    var left, right;

    if (str.length <= maxLength) return str;

    // length of beginning part      
    left = Math.ceil(maxLength / 2);

    // start index of ending part   
    right = str.length - Math.floor(maxLength / 2) + 1;   

    return str.substr(0, left) + midChar + str.substring(right);
}

请注意,我在UTF-8中使用了一个填充字符超过1个字节。

答案 10 :(得分:1)

如果您使用的是Ext.js,则可以使用Ext.util.Format.ellipsis功能。

答案 11 :(得分:1)

我赞成Kooilnc的解决方案。非常好的紧凑型解决方案。我想谈一个小边缘案例。如果某人因任何原因输入了一个非常长的字符序列,它就不会被截断:

function truncate(str, n, useWordBoundary) {
    var singular, tooLong = str.length > n;
    useWordBoundary = useWordBoundary || true;

    // Edge case where someone enters a ridiculously long string.
    str = tooLong ? str.substr(0, n-1) : str;

    singular = (str.search(/\s/) === -1) ? true : false;
    if(!singular) {
      str = useWordBoundary && tooLong ? str.substr(0, str.lastIndexOf(' ')) : str;
    }

    return  tooLong ? str + '&hellip;' : str;
}

答案 12 :(得分:1)

通过快速谷歌搜索,我发现this ...这对您有用吗?

/**
 * Truncate a string to the given length, breaking at word boundaries and adding an elipsis
 * @param string str String to be truncated
 * @param integer limit Max length of the string
 * @return string
 */
var truncate = function (str, limit) {
    var bits, i;
    if (STR !== typeof str) {
        return '';
    }
    bits = str.split('');
    if (bits.length > limit) {
        for (i = bits.length - 1; i > -1; --i) {
            if (i > limit) {
                bits.length = i;
            }
            else if (' ' === bits[i]) {
                bits.length = i;
                break;
            }
        }
        bits.push('...');
    }
    return bits.join('');
};
// END: truncate

答案 13 :(得分:0)

如果你想用 css 而不是 JavaScript;

.textShortDesc { /*Here we have determined the max number of lines.*/
    display: block; /* or inline-block */
    -o-text-overflow: ellipsis; /* Opera < 11*/
    text-overflow: ellipsis; /* IE, Safari (WebKit), Opera >= 11, FF > 6 */
    word-wrap: break-word;
    overflow: hidden;
    max-height: 2em; /*max-height/line-height=rowCount */
    line-height: 1em;
}

答案 14 :(得分:0)

这是我对单词边界的解决方案。

let s = "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
let s_split = s.split(/\s+/);
let word_count = 0;
let result = "";
//1
for(let i = 0; word_count < 100; i++){
  word_count += s_split[i].length+1;
  result += (s_split[i] + " ");
}
console.log(result);
// 2
word_count = 0;
result = s_split.reduce((x,y)=>{
  word_count+=(y.length+1);
  if(word_count>=100) return x;
  else return x+" "+y;}, "").substring(1);
console.log(result);

答案 15 :(得分:0)

我总是使用cuttr.js library to truncate strings并添加自定义省略号:

new Cuttr('.container', {
  //options here
  truncate: 'words',
  length: 8,
  ending: '... ►'
});
<script src="https://unpkg.com/cuttr@1.1.1/dist/cuttr.min.js"></script>
<p class="container">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. </p>

这是迄今为止最简单的方法(并且没有任何依赖性),我知道用JS剪切字符串,它也可以作为jQuery插件使用。

答案 16 :(得分:0)

('long text to be truncated').replace(/(.{250})..+/, "$1…");

以某种方式,以上代码不适用于vuejs应用程序中的某种复制粘贴或书面文本。因此,我使用了lodash truncate,现在可以正常使用了。

_.truncate('long text to be truncated', { 'length': 250, 'separator': ' '});

答案 17 :(得分:0)

.wrap{
  text-overflow: ellipsis
  white-space: nowrap;
  overflow: hidden;
  width:"your desire width";
}
<p class="wrap">He this is code</p>

答案 18 :(得分:0)

聪明的地方: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))

答案 19 :(得分:0)

我喜欢使用.slice()第一个参数是起始索引,第二个参数是结束索引。介于两者之间的一切就是您得到的回报。

var long = "hello there! Good day to ya."
// hello there! Good day to ya.

var short  = long.slice(0, 5)
// hello

答案 20 :(得分:0)

我最近不得不这样做,结果是:

/**
 * Truncate a string over a given length and add ellipsis if necessary
 * @param {string} str - string to be truncated
 * @param {integer} limit - max length of the string before truncating
 * @return {string} truncated string
 */
function truncate(str, limit) {
    return (str.length < limit) ? str : str.substring(0, limit).replace(/\w{3}$/gi, '...');
}

对我感觉很好,干净:)

答案 21 :(得分:0)

纠正Kooilnc的解决方案:

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

如果不需要截断,则返回字符串值而不是String对象。

答案 22 :(得分:0)

使用以下代码

 function trancateTitle (title) {
    var length = 10;
    if (title.length > length) {
       title = title.substring(0, length)+'...';
    }
    return title;
}

答案 23 :(得分:0)

c_harm的回答在我看来是最好的。请注意,如果您想使用

"My string".truncate(n)

你必须使用regexp对象构造函数而不是文字。此外,转换它时你必须逃离\S

String.prototype.truncate =
    function(n){
        var p  = new RegExp("^.{0," + n + "}[\\S]*", 'g');
        var re = this.match(p);
        var l  = re[0].length;
        var re = re[0].replace(/\s$/,'');

        if (l < this.length) return re + '&hellip;';
    };

答案 24 :(得分:-1)

此函数也会截断空格和单词部分。(例如:母亲进入蛾......)

String.prototype.truc= function (length) {
        return this.length>length ? this.substring(0, length) + '&hellip;' : this;
};

<强>用法:

"this is long length text".trunc(10);
"1234567890".trunc(5);

<强>输出:

  

这是......

     

... 12345