Forum Discussion
Thanks for that snippet. Maybe I've missed something but how do you avoid truncating mid-word?
Hi cblown,
Freemarker has two built-ins for strings that would probably come in handy for that.
index_of - http://freemarker.sourceforge.net/docs/ref_builtins_string.html#ref_builtin_index_of
last_index_of - http://freemarker.sourceforge.net/docs/ref_builtins_string.html#ref_builtin_last_index_of
Both of these work kind of like a search function for a string, and they both also allow you to specify a starting index to search from.
So let's say you know you want about 250 characters. You could use that as the starting point for your search to look for a space. index_of can be used to get the remainder of the word at 250 characters (so you'll likely wind up with a few more than 250). If you have a hard limit and want no more than 250 characters, you should probably use last_index_of, so that it will search backwards. Keep in mind that the string indexes actually start at 0 for the first character, so if you want no more than 250 characters, you should actually use a starting index of 249.
index_of and last_index_of will both return an index of the match, or -1 if no match exists. You'll probably want to assign this index to a variable. So if the index is greater than 0, you can just use that variable in place of the hard-coded "247". If the index is less than 0 for some reason (ie. a really long string of text with no breaks), your best bet would probably be to just go ahead and use the "default" value (ie. 247 or whatever you choose). That probably won't ever happen, but your code should probably handle it just in case.
I hope this helps!
Related Content
- 4 years ago
- 2 years ago