I needed to generate some short intros/teasers from longer body text today, and not having anything readily at hand, decided to see what was available at tagSwap. Searching for “truncate” brought up two tags, one based on the other.
The first is [string_truncate] by John Burwell. It’s pretty straightforward. Pass in a string and the desired length, and it will return the string truncated to exactly the specified length, plus an optional string to indicate the continuation (for instance, an ellipsis). It checks to see if the source string is shorter than the given length, in which case it returns the string unaltered.
This looked like it would do the trick, but I decided to check out the other tag anyway. It was [gf_lowtext] by Gaetano Frascolla. Gaetano’s tag is based on John’s, but adds an additional check to see if the truncated string ends with a space. If not, it assumes a word is being split, and truncates an additional character until it reaches a space before returning the result.
It’s a nice enhancement, but only checking for a space presents some potential limitations. First of all, there are plenty of other whitespace characters that may break up words, and secondly, it doesn’t take punctuation and other special characters into consideration. I’d rather not see the result end with a comma or apostrophe, especially when followed by an ellipsis.
It seemed as if a little regex and some elbow grease might provide me with a few additional enhancements, so I grabbed Gaetano’s tag and got to work.