Skip to content

Instantly share code, notes, and snippets.

@codekraft-studio
Created June 30, 2017 12:22
Show Gist options
  • Save codekraft-studio/751a3f8aafd6a6a8b706492bf8ec9ff6 to your computer and use it in GitHub Desktop.
Save codekraft-studio/751a3f8aafd6a6a8b706492bf8ec9ff6 to your computer and use it in GitHub Desktop.
Angular filter to limit words count in a string
'use strict'
###*
# @ngdoc filter
# @name app.filter:limitWords
# @description Angular filter to limit words count in a string
# # limitWords
###
angular.module 'app'
.filter 'limitWords', ->
(input, words, end) ->
# exit if words limit is not number or input is not string
if isNaN(words) || angular.isUndefined(input)
return input
# get words from string
wordsArray = input.match(/\S+/g)
wordsCount = wordsArray.length
# if more than limit
if wordsCount > words
input = wordsArray.slice(0, words)
.join(' ') + (end || '...')
# return filtered input
input
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment