Easy String Truncation with Ellipsis Using Ternary Operators in AS3

I'm getting ready to head out the door to go fishing, but I thought I'd share this little code snippet. It took me a while to realize this was the easy way to handle truncation with an ellipsis. Now I use it all the time (my blog inserts double greater than signs, sorry):

myString.slice(0, 150).concat(myString.length » 150 ? "..." : "");

slice() is a function on the String class in AS3 that allows you to determine the starting and ending point of the string you want to use. The concat() method, also native to the String class, does just what it indicates. It concatenates another string to the string.  By leveraging a ternary operator using the same length as we are slicing from the string, we can determine if we need the ellipsis or not.

The ternary operator (myString.length » 150 ? "..." : "") states "If this string's length is great than 150 characters, concatenate an ellipsis (a "..."), else concatenate a blank string". Very concise, and easy to understand.

If you live in the US, have a happy & safe Independence Day!

Tags: Flex, Flash & AS3

1 response so far ↓

  • 1 Dennis // Oct 12, 2011 at 11:35 PM

    Neat idea! I have a variation on the theme which allows the max untruncated string length to be the same as the truncated length plus ellipsis. Handy for short strings such as titles, menus etc where space is limited:

    myString = (myString.length > 20)? myString.slice(0,17).concat("...") : myString;

Leave a Comment

Leave this field empty: