Last active
August 29, 2015 14:16
-
-
Save guillaumepiot/dd5b05470636e2a5c470 to your computer and use it in GitHub Desktop.
COFFEESCRIPT - Abbreviate string
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
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