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