Limit the length of a string with AngularJS

306,961

Solution 1

Edit The latest version of AngularJSoffers limitTo filter.

You need a custom filter like this:

angular.module('ng').filter('cut', function () {
        return function (value, wordwise, max, tail) {
            if (!value) return '';

            max = parseInt(max, 10);
            if (!max) return value;
            if (value.length <= max) return value;

            value = value.substr(0, max);
            if (wordwise) {
                var lastspace = value.lastIndexOf(' ');
                if (lastspace !== -1) {
                  //Also remove . and , so its gives a cleaner result.
                  if (value.charAt(lastspace-1) === '.' || value.charAt(lastspace-1) === ',') {
                    lastspace = lastspace - 1;
                  }
                  value = value.substr(0, lastspace);
                }
            }

            return value + (tail || ' …');
        };
    });

Usage:

{{some_text | cut:true:100:' ...'}}

Options:

  • wordwise (boolean) - if true, cut only by words bounds,
  • max (integer) - max length of the text, cut to this number of chars,
  • tail (string, default: ' …') - add this string to the input string if the string was cut.

Another solution: http://ngmodules.org/modules/angularjs-truncate (by @Ehvince)

Solution 2

Here is the simple one line fix without css.

{{ myString | limitTo: 20 }}{{myString.length > 20 ? '...' : ''}}

Solution 3

I know this is late, but in the latest version of angularjs (I'm using 1.2.16) the limitTo filter supports strings as well as arrays so you can limit the length of the string like this:

{{ "My String Is Too Long" | limitTo: 9 }}

which will output:

My String

Solution 4

You can simply add a css class to the div, and add a tool tip via angularjs so that trimmed text will be visible on mouse over.

<div class="trim-info" tooltip="{{modal.title}}">{{modal.title}}</div>

   .trim-info {
      max-width: 50px;
      display: inline-block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;  
      line-height: 15px;
      position: relative;
   }

Solution 5

I had a similar problem, here is what i did:

{{ longString | limitTo: 20 }} {{longString.length < 20 ? '' : '...'}}
Share:
306,961

Related videos on Youtube

Alan2
Author by

Alan2

Updated on November 17, 2020

Comments

  • Alan2
    Alan2 over 3 years

    I have the following:

    <div>{{modal.title}}</div>
    

    Is there a way that I could limit the length of the string to say 20 characters?

    And an even better question would be is there a way that I could change the string to be truncated and show ... at the end if it's more than 20 characters?

  • Ehvince
    Ehvince over 10 years
    There's an equivalent at angular-modules: ngmodules.org/modules/angularjs-truncate
  • Parixit
    Parixit about 10 years
    provide some more details also
  • Anton Bessonov
    Anton Bessonov almost 10 years
    angularjs-truncate isn't solution, but your IS solution. Thank you! Make it as module!
  • Chris Russo
    Chris Russo almost 10 years
    text-overflow: ellipsis, nice one.
  • Larry
    Larry over 9 years
    this technique, while awesome, prevents text from wrapping
  • Snæbjørn
    Snæbjørn over 9 years
    This solution is missing the "...". The result should be: "My String..."
  • slim
    slim over 9 years
    I'm not seeing the ellipsis here: plnkr.co/edit/HyAejS2DY781bqcT0RgV?p=preview. Can you elaborate?
  • Thales P
    Thales P over 9 years
    @epokk There's a way to allow user to, after click on the three dots, show the complete uncut text? Like a "show more"? Thanks!
  • Nahn
    Nahn over 9 years
    What @Snæbjørn is saying is that the person who asked the question preferred a solution that inserts "..." at the end of the truncated string. Govan's answer does that.
  • slim
    slim over 9 years
    @Nahn thanks for pointing that out. I probably should have made a comment to EpokK's answer instead of another answer.
  • Tom Harrison
    Tom Harrison over 9 years
    Simple and elegant. Instead of '...' you can also use the HTML entity for ellipsis: '&hellip;'
  • mcranston18
    mcranston18 about 9 years
    Can I suggest adding a return in case the input value is dynamic? i.e. if (!input) {return;} Otherwise there will be JS console errors
  • Anam
    Anam about 9 years
    @mcranston18 added. Thank you.
  • S Vinesh
    S Vinesh about 9 years
    this works fine when we use it like this {{post.post_content | cut:true:100:' ...'}} But fails when i use like this <span ng-bind-html="trustedHtml(post.post_content| cut:true:100:' ...')"></span> Because i am forced to use it with trusted html in my case
  • pdizz
    pdizz over 8 years
    The wordwise limit is a nice feature that doesnt seem to exist in the default "limitTo"
  • aidan
    aidan over 8 years
    This is the correct answer. My general rule is: "don't do in JavaScript that which can be done in CSS".
  • Ellone
    Ellone over 8 years
    Is there a simple way filterTo to make the string truncated at the first space after the position limit ? So it doesn't split at the middle of a word.
  • Robert
    Robert about 8 years
    This only works for text with one line per paragraph. See for multiline css-tricks.com/line-clampin (not all browsers support that).
  • Cowwando
    Cowwando about 8 years
    probably the most painless solution. Still keep in mind that filters are relatively heavy and this might have performance issues on huge ng-repeat list! :)
  • JDDelgado
    JDDelgado about 8 years
    I just wanted to improve this answer a bit, if the last word of the wrapping has a comma or dot at the end, it ends up with something like .... or ,... which I hate, so It can be improved by adding the following right after the lastspace != -1 if statement if (value.charAt(lastspace-1) == '.' || value.charAt(lastspace-1) == ',') { lastspace = lastspace - 1; }
  • chakeda
    chakeda almost 8 years
    This also works if you are trying to limit the length of an array ng-repeat.
  • Moe Far
    Moe Far almost 8 years
    @EpokK: Thanks. how about adding read more link if cut happens
  • axd
    axd almost 8 years
    awesome! is there a way to cut after a number of lines, rather than after a number of characters?
  • Govan
    Govan almost 8 years
    @axd You need to try that in css or write a directive to achieve that.
  • Henrique M.
    Henrique M. over 7 years
    Simplest approach, yet functional. But it assumes that every title would have more than 20 characters and this, in some cases, may be unexpected.
  • erier
    erier over 7 years
    This is the best answer. The performance hit should be negligible with a reasonable number of ng-repeat. If you're bringing back hundred's of ng-repeat with content that needs to be truncated then might need to go back to drawing board. Nice answer, @Govan
  • Ne AS
    Ne AS over 7 years
    Please what if I want to apply a limit to the total length of two strings?
  • Govan
    Govan over 7 years
    @Lig Please elaborate. Any example of what you require will be helpful.
  • Ne AS
    Ne AS over 7 years
    @Govan lets say that I have $scope.string1 and $scope.string2. In the HTML I display {{string1}} {{string2}}. I want that the total of charatecters of the two string have a limit. How can I do that?
  • Govan
    Govan over 7 years
    @Lig have to write custom filter for this. If you wish ask a separate question and post the link here. I ll answer that.
  • shaikh
    shaikh over 7 years
    But this solution doesn't have support for word wise cut
  • BSMP
    BSMP over 6 years
    Is there any chance you posted this answer on the wrong question? This doesn't appear to have anything to do with limiting the length of a string with AngularJS.
  • Usman Iqbal
    Usman Iqbal over 6 years
    How can i do this with ng-bind-html ?
  • Ignacio Vazquez
    Ignacio Vazquez about 6 years
    Its a perfect css-pure solution for single line - wont work if you need multiple lines because of the 'white-space: nowrap; '
  • Ignacio Vazquez
    Ignacio Vazquez about 6 years
    I would remove the whitespace between both outputs to avoid line break
  • Robbie Smith
    Robbie Smith almost 5 years
    The line-height isn't necessary since you might be dealing with different sizes/heights of text. With the line-height in place you end up truncating the foot of the g or j or y
  • LiefLayer
    LiefLayer over 4 years
    @ThalesP Of course this is an old question but to do something like that (click and show the text) I just put a ng-click="ctrl.cutting=!ctrl.cutting; ctrl.cut2 = ctrl.cutting ? 50 : 5000;" in my html element that contains the text and 2 variables vm.cutting = true; vm.cut2 = 50; on my controller. If I click on my text the limit will be 5000 instead of 50.
  • Thales P
    Thales P almost 4 years
    @LiefLayer Hehehe, really old :) Tkx