Created
August 13, 2014 13:48
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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; | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{'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 --> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice