Limit the length of a string with AngularJS
Solution 1
Edit
The latest version of AngularJS
offers 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 ? '' : '...'}}
Related videos on Youtube
Alan2
Updated on November 17, 2020Comments
-
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?-
Ufuk Hacıoğulları over 10 years
-
-
Ehvince over 10 yearsThere's an equivalent at angular-modules: ngmodules.org/modules/angularjs-truncate
-
Parixit about 10 yearsprovide some more details also
-
Anton Bessonov almost 10 yearsangularjs-truncate isn't solution, but your IS solution. Thank you! Make it as module!
-
Chris Russo almost 10 yearstext-overflow: ellipsis, nice one.
-
Larry over 9 yearsthis technique, while awesome, prevents text from wrapping
-
Snæbjørn over 9 yearsThis solution is missing the "...". The result should be: "My String..."
-
slim over 9 yearsI'm not seeing the ellipsis here: plnkr.co/edit/HyAejS2DY781bqcT0RgV?p=preview. Can you elaborate?
-
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 over 9 yearsWhat @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 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 over 9 yearsSimple and elegant. Instead of
'...'
you can also use the HTML entity for ellipsis:'…'
-
mcranston18 about 9 yearsCan 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 about 9 years@mcranston18 added. Thank you.
-
S Vinesh about 9 yearsthis 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 over 8 yearsThe wordwise limit is a nice feature that doesnt seem to exist in the default "limitTo"
-
aidan over 8 yearsThis is the correct answer. My general rule is: "don't do in JavaScript that which can be done in CSS".
-
Ellone over 8 yearsIs 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 about 8 yearsThis only works for text with one line per paragraph. See for multiline css-tricks.com/line-clampin (not all browsers support that).
-
Cowwando about 8 yearsprobably 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 about 8 yearsI 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 almost 8 yearsThis also works if you are trying to limit the length of an array
ng-repeat
. -
Moe Far almost 8 years@EpokK: Thanks. how about adding
read more
link if cut happens -
axd almost 8 yearsawesome! is there a way to cut after a number of lines, rather than after a number of characters?
-
Govan almost 8 years@axd You need to try that in css or write a directive to achieve that.
-
Henrique M. over 7 yearsSimplest approach, yet functional. But it assumes that every title would have more than 20 characters and this, in some cases, may be unexpected.
-
erier over 7 yearsThis 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 over 7 yearsPlease what if I want to apply a limit to the total length of two strings?
-
Govan over 7 years@Lig Please elaborate. Any example of what you require will be helpful.
-
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 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 over 7 yearsBut this solution doesn't have support for word wise cut
-
BSMP over 6 yearsIs 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 over 6 yearsHow can i do this with ng-bind-html ?
-
Ignacio Vazquez about 6 yearsIts a perfect css-pure solution for single line - wont work if you need multiple lines because of the 'white-space: nowrap; '
-
Ignacio Vazquez about 6 yearsI would remove the whitespace between both outputs to avoid line break
-
Robbie Smith almost 5 yearsThe 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 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 almost 4 years@LiefLayer Hehehe, really old :) Tkx