Skip to content

Instantly share code, notes, and snippets.

@a-r-m-i-n
Created August 13, 2014 13:48
Show Gist options
  • Save a-r-m-i-n/6c1b161a8f20763e1cf1 to your computer and use it in GitHub Desktop.
Save a-r-m-i-n/6c1b161a8f20763e1cf1 to your computer and use it in GitHub Desktop.
AngularJS filter to crop text and respect word boundaries
'use strict';
app.filter('crop', function(){
return function(input, limit, respectWordBoundaries, suffix){
if (input === null || input === undefined || limit === null || limit === undefined || limit === '') {
return input;
}
if (angular.isUndefined(respectWordBoundaries)) {
respectWordBoundaries = true;
}
if (angular.isUndefined(suffix)) {
suffix = '...';
}
if (input.length <= limit) {
return input;
}
limit = limit - suffix.length;
var trimmedString = input.substr(0, limit);
if (respectWordBoundaries) {
return trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" "))) + suffix;
}
return trimmedString + suffix;
}
});
{{'My super cool text which is very long' | crop:25}} <!-- My super cool text... -->
{{'My super cool text which is very long' | crop:25:false}} <!-- My super cool text whi... -->
{{'My super cool text which is very long' | crop:25:true:'!!!'}} <!-- My super cool text whi!!! -->
{{'My super cool text which is very long' | crop:999:true:'!!!'}} <!-- My super cool text which is very long -->
@ryanjeric
Copy link

Thanks you.

@neilmaledev
Copy link

Thanks..

I made some changes

insert below the first if
input = String(input).replace(/<[^>]+>/gm, '');

remove line 18
limit = limit - suffix.length;

purpose of changes

to disregard html tags length

<p>Hello</p> = 12 chars
Hello = 5 chars

@dougdot3
Copy link

dougdot3 commented Feb 5, 2017

Beautiful.

@demiansolano
Copy link

nice

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