Skip to content

Instantly share code, notes, and snippets.

@emyann
Created June 16, 2016 20:32
Show Gist options
  • Save emyann/f36afc4c1ea48140fcd06b18a72fce69 to your computer and use it in GitHub Desktop.
Save emyann/f36afc4c1ea48140fcd06b18a72fce69 to your computer and use it in GitHub Desktop.
AngularJs filter to truncate text
angular
.module('ng')
.filter('truncate', function () {
/**
* @param {boolean} wordwise - if true, cut only by words bounds
* @param {string} max - max length of the text, cut to this number of chars
* @param {string} tail - add this string to the input string if the string was cut
*/
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) {
if (value.charAt(lastspace-1) == '.' || value.charAt(lastspace-1) == ',') {
lastspace = lastspace - 1;
}
value = value.substr(0, lastspace);
}
}
return value + (tail || ' …');
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment