Smart way to truncate long strings

自闭症网瘾萝莉.ら 提交于 2019-11-26 03:36:40

问题


Does anyone have a more sophisticated solution/library for truncating strings with JavaScript and putting an ellipsis on the end, than the obvious one:

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

回答1:


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

Now you can do:

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

If by 'more sophisticated', you mean truncating at the last word boundary of a string, then this might be what you want:

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

now you can do:

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

If you don't want to extend native objects, you can use:

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



回答2:


Note that this only needs to be done for Firefox.

All other browsers support a CSS solution (see 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 */
}

The irony is I got that code snippet from Mozilla MDC.




回答3:


Use either lodash's truncate

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

or underscore.string's truncate.

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



回答4:


There are valid reasons people may wish to do this in JavaScript instead of CSS.

To truncate to 8 characters (including ellipsis) in JavaScript:

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

or

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



回答5:


Here's my solution, which has a few improvements over other suggestions:

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

It:

  • Truncates on the first space after 25 characters
  • Extends the JavaScript String object, so it can be used on (and chained to) any string.
  • Will trim the string if truncation results in a trailing space;
  • Will add the unicode hellip entity (ellipsis) if the truncated string is longer than 25 characters



回答6:


Best function I have found. Credit to text-ellipsis.

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

Examples:

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"



回答7:


Most modern Javascript frameworks (JQuery, Prototype, etc...) have a utility function tacked on to String that handles this.

Here's an example in Prototype:

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

This seems like one of those functions you want someone else to deal with/maintain. I'd let the framework handle it, rather than writing more code.




回答8:


All modern browsers now support a simple CSS solution for automatically adding an ellipsis if a line of text exceeds the available width:

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

(Note that this requires the width of the element to be limited in some way in order to have any effect.)

Based on https://css-tricks.com/snippets/css/truncate-string-with-ellipsis/.

It should be noted that this approach does not limit based on the number of characters. It also does not work if you need to allow multiple lines of text.




回答9:


Perhaps I missed an example of where someone is handling nulls, but 3 TOP answers did not work for me when I had nulls ( Sure I realize that error handling is and million other things is NOT the responsibility of the person answering the question, but since I had used an existing function along with one of the excellent truncation ellipsis answers I thought I would provide it for others.

e.g.

javascript:

news.comments

using truncation function

news.comments.trunc(20, true);

However, on news.comments being null this would "break"

Final

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

trunc function courtesy of 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_;
 };

My simple null checker (checks for literal "null" thing too (this catches undefined, "", null, "null", etc..)

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



回答10:


Sometimes file names are numbered, where the index may be at the beginning or the end. So I wanted to shorten from the center of the string:

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

Be aware that I used a fill character here with more than 1 byte in UTF-8.




回答11:


You can use the Ext.util.Format.ellipsis function if you are using Ext.js.




回答12:


I upvoted Kooilnc's solution. Really nice compact solution. There's one small edge case that I would like to address. If someone enters a really long character sequence for whatever reason, it won't get truncated:

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



回答13:


With a quick Googling I found this... Does that work for you?

/**
 * 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



回答14:


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

Somehow above code was not working for some kind of copy pasted or written text in vuejs app. So I used lodash truncate and its now working fine.

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



回答15:


c_harm's answer is in my opinion the best. Please note that if you want to use

"My string".truncate(n)

you will have to use a regexp object constructor rather than a literal. Also you'll have to escape the \S when converting it.

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



回答16:


Use following code

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



回答17:


Correcting Kooilnc's solution:

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

This returns the string value instead of the String object if it doesn't need to be truncated.




回答18:


I recently had to do this and ended up with:

/**
 * 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, '...');
}

Feels nice and clean to me :)




回答19:


I like using .slice() The first argument is the starting index and the second is the ending index. Everything in between is what you get back.

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

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



回答20:


Somewhere Smart :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))



回答21:


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



回答22:


This function do the truncate space and words parts also.(ex: Mother into Moth...)

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

usage:

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

output:

this is lo...

12345...



来源:https://stackoverflow.com/questions/1199352/smart-way-to-truncate-long-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!