Skip to content

Instantly share code, notes, and snippets.

@guillaumepiot
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guillaumepiot/dd5b05470636e2a5c470 to your computer and use it in GitHub Desktop.
Save guillaumepiot/dd5b05470636e2a5c470 to your computer and use it in GitHub Desktop.
COFFEESCRIPT - Abbreviate string
window.abbreviate = (str, max, suffix) ->
#
# Trim leading and trailing white space
#
str = str.replace /^\s+|\s+$/g, ""
#
# If the string is less than max, return it
#
if str.length <= max
return str
abbr = ''
#
# Split the string by word, separated by white space
#
str = str.split(' ')
#
# If we didn't receive a suffix as argument, use '...'
#
suffix = if typeof suffix != 'undefined' then suffix else ' ...'
max = max - suffix.length
i = 0
# How many word to we have?
len = str.length
#
# Loop through all the words, and keep added them until
# we reach the limit
#
while i < len
if (abbr + str[i]).length < max
abbr += str[i] + ' '
else
break
i++
# Remove the last added white space, and return
abbr.replace(/[ ]$/g, '') + suffix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment