Smart way to truncate long strings
Asked Answered
C

28

278

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) + "...";
}
Conchaconchie answered 29/7, 2009 at 10:44 Comment(2)
What do you mean by "more sophisticated"? Functions that take word boundaries into account?Protostele
And not truncating in the middle of HTML tags.Vitellin
M
528

Essentially, you check the length of the given string. If it's longer than a given length n, clip it to length n (substr or slice) and add html entity … (…) to the clipped string.

Such a method looks like

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

If by 'more sophisticated' you mean truncating at the last word boundary of a string then you need an extra check. First you clip the string to the desired length, next you clip the result of that to its last word boundary

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

You can extend the native String prototype with your function. In that case the str parameter should be removed and str within the function should be replaced with this:

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

More dogmatic developers may chide you strongly for that ("Don't modify objects you don't own". I wouldn't mind though). [edit 2023] A method to extend the String without tampering with its prototype may be to use a Proxy. See this stackblitz snippet.

An approach without extending the String prototype is to create your own helper object, containing the (long) string you provide and the beforementioned method to truncate it. That's what the snippet below does.

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>

Finally, you can use css only to truncate long strings in HTML nodes. It gives you less control, but may well be viable solution.

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>
Mudfish answered 29/7, 2009 at 10:56 Comment(23)
Should also consider having "hard" and "soft" limits, like, for example, if the string is longer than 500 character, truncate it to 400. This may be useful, when the user wants to see the whole text and clicks some link for it. If, as a result, you load just 1 or 2 chars more, it will look really ugly.Unmistakable
The second parameter to substr is a length so it should be substr(0,n) instead to limit it to the first n chars.Krute
Sorry to digg up that, but your first code has a bug. When the string is just the maximumlength, it truncate the last char. The good code may be this: return (this.length>n) ? this.substr(0,n-1)+'&hellip;': this;Alsatian
Excellent compact solution. This can also easily be adjusted to work in C#.Torosian
Don't modify objects you don't own. nczonline.net/blog/2010/03/02/…Refractive
I'm copy-pasting this!Squamosal
One thing you might consider is replacing the &hellip; with actual ellipsis (...) in your code example. If you are trying to use this for interacting with API's you'll want the non-HTML entity there.Ilka
Compact, but could do with some better variable names..plus this does not contain the ellipsis length in the target length.Turnkey
If the string is shorter than the number we enter it make a error and output "string"Quality
There is no lastIndexOf result checking... That's what @Quality is talking about. If you call it like "System.Web.AnotherCrazyException".trunc(20, true); you just got the ellipsis as return. I believe that the function should ignore the useWordBoundary in this cases. I've made an implementation like this: jsfiddle.net/xpn703foPathos
Works most of the time, but just an FYI I used this in another project and got a "Uncaught TypeError: Cannot read property 'trunc' of null"Callup
@TomStickel that's not a problem of the trunc extension method: if trunc is called on something that is not a string that something doesn't know a trunc method. So you should check the variable on which you call the trunc-method: if it's null or undefined or if it's not a string, a TypeError will be thrown.Mudfish
Ok, I liked your function a lot and just scrambling to meet deadline for the sprint ending tomorrow and so I just added an answer in to show what I did for the null issue that I had. Of hand I didn't have time to really think this through, but if you see an issue with my solution add-on to yours , please comment etc.. Thanks !Callup
Note that it's generally considered bad practice to modify native classes like String, Array, etc (see nczonline.net/blog/2010/03/02/…)Augustine
AWESOME JOB THANKSFortitude
Is there a way to export this extension from another file? Then import (es6) using something like: import trunc from 'blah.js'?Sirius
@Sirius Not in a browser environment (see developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…). You may need a transpiler. In nodejs you can export the method (function truncate) and bind it locally to String.prototype or bind the method to global.String.prototype.Mudfish
@Mudfish awesome, I'm using Babel to convert everything to vanilla js so I'll give it a shot, thanks!Sirius
Cool but truncate function unefficient - short strings will make the function evaluate 3 expression too many. You should use if(this.length>n){... return..} return thisPelagia
@RuneJeppesen you're right. Adjusted the methods. To my defense: the answer dates 7 years back ;)Mudfish
You need to add a semicolon at the end of "&hellip" otherwise it will just render "&hellip" instead of "...". Apart from that, works really well, good for shortening blog post previews. +1Mazzola
Maybe use '\u2026' instead of '&hellip;' (if you are running ReactJS).Ardelia
String.prototype.substr() is deprecated - Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time - MDN DocsNostology
P
80

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.

Pournaras answered 29/7, 2009 at 12:38 Comment(5)
mattsnider.com/css/css-string-truncation-with-ellipsis to make it work with FF as well.Storied
Wow this is a perfect solution for mobile Safari. Thank you!Brett
Very good CSS approach. There might be a note, that this only works with a single line of text (as intended by white-space: nowrap;). When it comes to more than one line you're stuck with JavaScript.Kampmann
It also only works for the entire element. If you want to truncate part of a string, without wrapping the bit you want to truncate in a span or other html element, this won't work e.g.: Your picture ('some very long picture filename truncated...') has been uploaded.Harvard
OP asked specifically for a javascript solutionSnooker
C
43

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…");
Cassaundracassava answered 10/10, 2016 at 21:50 Comment(3)
If you count the ellipsis, this will be 9 characters. If you need it to be 8 after truncation, use .replace(/^(.{7}).{2,}/, "$1…"); insteadKobarid
long and short are reserved as future keywords by older ECMAScript specifications (ECMAScript 1 till 3). See MDN: Future reserved keywords in older standardsSpecial
If you have newlines in your text use "s" so the "." can match line breaks. text.replace(/(.{100}).+/s, "$1...")Heteroousian
I
36

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...'
Intertexture answered 8/4, 2016 at 13:37 Comment(0)
K
17
('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': ' '});
Knute answered 10/7, 2019 at 15:15 Comment(3)
nice modern answer!Baleful
I would be curious to know what the text was. Was it using non-Latin characters?Cassaundracassava
It was a just a lorem ipsumKnute
P
13

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"
Printing answered 22/5, 2018 at 22:41 Comment(0)
A
12

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.

Augustine answered 20/3, 2012 at 17:42 Comment(3)
This is only useful for single line sentences, there is no way (so far that I know) to do a multi-line example via CSS.Shultz
Is there by any chance a way to make this do the ellipsis on the left instead of the right?Leuko
@Leuko I believe you can accomplish that by using text-direction: rtl and text-align: left. See davidwalsh.name/css-ellipsis-leftAugustine
J
7

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
Jankey answered 29/7, 2009 at 11:37 Comment(0)
D
7

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
Deaconry answered 23/1, 2019 at 20:8 Comment(1)
Simplest answer, no need for over-complicated answers.Crocodilian
S
6

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.

Searching answered 29/7, 2009 at 11:27 Comment(6)
I don't think jQuery has anything for this.Saltcellar
Underscore.js does - _('Hello world').truncate(5) => 'Hello...' _('Hello').truncate(10) => 'Hello'Inion
Pure Underscore does not seem to have truncate() either - you might need an extension such as underscore.string .Dag
This is totally the right answer. I don't know about underscore, but lodash has _.trunc which does exactly this.Appal
I think the right answer is to use lodash.trunc or underscore.string.truncate.Intertexture
This function is now called _.truncate in lodash. lodash.com/docs/4.17.15#truncateHeterotopia
E
4

Text-overflow: ellipsis is the property you need. With this and an overflow:hidden with a specific width, everything surpassing that will get the three period effect at the end ... Don't forget to add whitespace:nowrap or the text will be put in multiple lines.

.wrap{
  text-overflow: ellipsis
  white-space: nowrap;
  overflow: hidden;
  width:"your desired width";
}
<p class="wrap">The string to be cut</p>
Edh answered 26/3, 2019 at 12:43 Comment(4)
Brevity is acceptable, but fuller explanations are better.Shakti
mwilcox and Sean the Bean already posted this solution.Klemm
Can be used for one-line text onlyWin
The text-overflow: ellipsis is perfect!!Gratuitous
H
3

I always use the cuttr.js library to truncate strings and add custom ellipsis:

new Cuttr('.container', {
  //options here
  truncate: 'words',
  length: 8,
  ending: '... ►'
});
<script src="https://unpkg.com/[email protected]/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>

This is bar far the easiest method (and doesn't have any dependencies) I know to cut strings with JS and its also available as jQuery plugin.

Hybridism answered 6/8, 2020 at 18:44 Comment(0)
C
2

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 "";
      }
  }
Callup answered 7/12, 2015 at 17:31 Comment(5)
Here's a modified version - avoids use of prototype, incorporates null checking in the function, and has some test/demo usage. codepen.io/mahemoff/pen/LGEdzyImplication
Do you find prototype to be problematic? Just curiousCallup
The reason for my separate null check function is that it will actually check for null, undefined,NaN,empty string (""),0,false and "null" But overall I like your fxCallup
Yep, it's a matter of opinion and usage context, but prototype gets ugly when you are working with other libraries as they might also override the same thing. (Or in rare cases, a function of the same name might later be introduced as a standard language feature.)Implication
Yes, I agree with youCallup
H
2

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.

Headmost answered 31/1, 2018 at 16:40 Comment(0)
H
1

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
Hudnut answered 29/7, 2009 at 10:48 Comment(1)
What is STR? Where is that defined??Ere
K
1

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

Kneel answered 30/7, 2012 at 19:50 Comment(0)
U
1

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;
}
Upspring answered 11/12, 2013 at 15:24 Comment(0)
X
1

Use following code

 function trancateTitle (title) {
    var length = 10;
    if (title.length > length) {
       title = title.substring(0, length)+'...';
    }
    return title;
}
Xenos answered 23/4, 2014 at 14:1 Comment(0)
R
1

Here are my solutions with word boundary.

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);
Radbun answered 3/12, 2020 at 16:34 Comment(0)
H
1

I'm not sure if this qualifies as smart, but it's succinct and simple:

truncateStringToLength (string, length) {
  return (string.length > length)
    ? `${string.substring(0, length)} &hellip;`
    : string
}

… then:

truncateStringToLength('Lorem ipsum dolor sit amet, consetetur sadipscing', 20)
Hailee answered 20/3, 2022 at 11:35 Comment(0)
S
0

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;';
    };
Saccharoid answered 27/2, 2013 at 9:11 Comment(2)
Every heard of commenting and proper variable naming?Anamorphoscope
@Anamorphoscope the code is copied and modified from another answer above, no need to be so rude and snarky.Saccharoid
C
0

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.

Conte answered 19/11, 2014 at 0:12 Comment(2)
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post.Loden
Ah I see the distinction now. Thanks for the references. I did want to leave a comment with the hopes that @Kooilnc would see it, and possibly edit the accepted answer if he or she agreed, but didn't have the reputation.Conte
C
0

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

Chevrotain answered 31/1, 2017 at 15:26 Comment(1)
That could make the resulting string 3 chars longer than limit.Headmost
D
0

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))
Dilemma answered 22/2, 2019 at 7:41 Comment(0)
A
0

If you want to do it with css instead of 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;
}
Ahab answered 30/4, 2021 at 3:11 Comment(0)
D
0

(JS) Using Slice and Template Literals.

${myString}.slice(0, 20) ...

Dyspeptic answered 16/2, 2023 at 13:54 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Simone
G
0

Re-implementation of Lodash truncate in modern JS + TypeScript :

  • Supports omission/ellipsis ("...")
  • Configurable separator pattern (in general you want " ")
  • Configurable max length (default is 30)
// File truncate.ts

type Options = {
  /**
   * The maximum string length.
   *
   * Default: 30
   */
  length?: number;

  /**
   * The string to indicate text is omitted.
   *
   * Also named [ellipsis](https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow)
   *
   * Default: "...", you might want to use "…" (&hellip; U+02026) instead
   */
  omission?: string;

  /**
   * The separator pattern to truncate to.
   *
   * Default: none
   */
  separator?: string;
};

/**
 * Truncates a string if it's longer than the given maximum length.
 * The last characters of the truncated string are replaced with the omission
 * string which defaults to "...".
 *
 * @param str The string to truncate
 * @param options The options object
 * @returns The truncated string
 */
export function truncate(str: string, options?: Options) {
  // https://mcmap.net/q/107998/-smart-way-to-truncate-long-strings
  // https://github.com/Maggi64/moderndash/issues/155
  // https://lodash.com/docs/4.17.15#truncate

  const { length = 30, omission = '...', separator } = options ?? {};

  if (str.length <= length) {
    return str;
  }

  let maxLength = length - omission.length;
  if (maxLength < 0) {
    maxLength = 0;
  }
  const subString = str.slice(
    0,
    // FYI .slice() is OK if maxLength > text.length
    maxLength
  );

  return (separator ? subString.slice(0, subString.lastIndexOf(separator)) : subString) + omission;
}

Passes all tests from Lodash:

// File truncate.test.ts

import { truncate } from './truncate';

// Copy-pasted and adapted from https://github.com/lodash/lodash/blob/c7c70a7da5172111b99bb45e45532ed034d7b5b9/test/truncate.spec.js
// See also https://github.com/lodash/lodash/pull/5815

const string = 'hi-diddly-ho there, neighborino';

it('should use a default `length` of `30`', () => {
  expect(truncate(string)).toBe('hi-diddly-ho there, neighbo...');
});

it('should not truncate if `string` is <= `length`', () => {
  expect(truncate(string, { length: string.length })).toBe(string);
  expect(truncate(string, { length: string.length + 2 })).toBe(string);
});

it('should truncate string the given length', () => {
  expect(truncate(string, { length: 24 })).toBe('hi-diddly-ho there, n...');
});

it('should support a `omission` option', () => {
  expect(truncate(string, { omission: ' [...]' })).toBe('hi-diddly-ho there, neig [...]');
});

it('should support empty `omission` option', () => {
  expect(truncate(string, { omission: '' })).toBe('hi-diddly-ho there, neighborin');
});

it('should support a `length` option', () => {
  expect(truncate(string, { length: 4 })).toBe('h...');
});

it('should support a `separator` option', () => {
  expect(truncate(string, { length: 24, separator: ' ' })).toBe('hi-diddly-ho there,...');
});

it('should treat negative `length` as `0`', () => {
  [0, -2].forEach(length => {
    expect(truncate(string, { length })).toBe('...');
  });
});

it('should work as an iteratee for methods like `_.map`', () => {
  const actual = [string, string, string].map(str => truncate(str));
  const truncated = 'hi-diddly-ho there, neighbo...';

  expect(actual).toEqual([truncated, truncated, truncated]);
});
Gross answered 8/2 at 15:14 Comment(0)
A
-1

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

Alexio answered 27/9, 2017 at 11:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.