Instantly share code, notes, and snippets.

Embed
What would you like to do?
Truncate Filter for AngularJS v1.0
// add the filter to your application module
angular.module('yourAppName', ['filters']);
/**
* Truncate Filter
* @Param string
* @Param int, default = 10
* @Param string, default = "..."
* @return string
*/
angular.module('filters', []).
filter('truncate', function () {
return function (text, length, end) {
if (isNaN(length))
length = 10;
if (end === undefined)
end = "...";
if (text.length <= length || text.length - end.length <= length) {
return text;
}
else {
return String(text).substring(0, length-end.length) + end;
}
};
});
/**
* Example - see the jsfiddle: http://jsfiddle.net/tUyyx/
*
* var myText = "This is an example.";
*
* {{myText|truncate}}
* {{myText|truncate:5}}
* {{myText|truncate:25:" ->"}}
*
* Output
* "This is..."
* "Th..."
* "This is an e ->"
*
*/
@ultrawebsites

This comment has been minimized.

ultrawebsites commented Feb 24, 2013

It'd probably be worth adding in these two lines to the function too:

    if (text == null || text.length == 0)
        return null;

Cheers
Matt

@jfreal

This comment has been minimized.

jfreal commented Jun 11, 2013

Thanks for this.

@turbohappy

This comment has been minimized.

turbohappy commented Jul 23, 2013

Excellent, thanks.

@scottywakefield

This comment has been minimized.

scottywakefield commented Aug 9, 2013

Brilliant!

I also added a check for strings as I might be passing numeric as well. I just used angular.isString(text):

if (!angular.isString(text))
  return text;
@isRuslan

This comment has been minimized.

isRuslan commented Oct 17, 2013

You could probably use:

length = length || 10;
end = end || '...';

instead of:

if (isNaN(length))
  length = 10;

if (end === undefined)
  end = "...";
@mohsen1

This comment has been minimized.

mohsen1 commented Jul 29, 2014

Use unicode character() for ellipsis instead of dot-dot-dot(...). This helps accessibility. VoiceOver will not read "dot dot dot" and handles it better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment