Skip to content

Instantly share code, notes, and snippets.

@jh3
Last active August 29, 2015 14:03
Show Gist options
  • Save jh3/9306e8f8bbf24f2a0a6c to your computer and use it in GitHub Desktop.
Save jh3/9306e8f8bbf24f2a0a6c to your computer and use it in GitHub Desktop.
AngularJS filter of Drupal's truncate_utf8() function
app.filter "truncateText", ->
(string, maxLength, wordsafe = false, addEllipsis = false, minWordsafeLength = 1) ->
ellipsis = ''
maxLength = Math.max(maxLength, 0)
minWordsafeLength = Math.max(minWordsafeLength, 0)
# Remove HTML tags
string = string.replace(/<(?:.|\n)*?>/gm, '')
# No truncation needed, so don't add ellipsis, just return.
return string if (string.length <= maxLength)
if (addEllipsis)
# Truncate ellipsis in case max_length is small.
ellipsis = "...".substr(0, maxLength)
maxLength -= ellipsis.length
maxLength = Math.max(maxLength, 0)
# Do not attempt word-safe if lengths are bad.
wordsafe = false if (maxLength <= minWordsafeLength)
if (wordsafe)
# Find the last word boundary, if there is one within minWordsafeLength
# to maxLength characters
re = new RegExp('^(.{' + minWordsafeLength + ',' + maxLength + '})')
match = string.match(re)
string = if match[1] then match[1] else string.substr(0, maxLength)
else
string = string.substr(0, maxLength)
string += ellipsis if addEllipsis
return string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment