20 Sep Use regex to remove the last comma or character
Many saxotech tags output a list of objects: newslist, contentlist, links, etc. The object files that create the markup for those tags have a concept of a wrapper object file and item object file. For example, the newlist tag’s wrapper file is news.pbo and its item object file is newsitem.pbo. newsitem.pbo creates the markup for each item in the list.
Sometimes when using these wrapper and object files, you are simply creating a list of objects separated by a comma or some delimiter, but you don’t want that last one to show. Here are the scenarios we’ve experienced and how we solved it.
1. The item object file has the <%isLastItem%> variable
This one is easy. If the item object file has <%isLastItem%>, you can just use object script to not output the last comma.
Newsitem.pbo has this variable, and we would set it up like this:
The object script simply says, if this is not the last item in the list, print a ‘,’.
Most common list tags have this variable available in the item files. It is often also used to know when to close html elements.
2. The item object file doesn’t have <%isLastItem%>
Although this variable is available in many of the tag object files, we occasionally come across the ones where it isn’t available. For example, this variable isn’t available in NewsItemTaxonomyWordItem.pbo.
When we need the last comma to be removed, we use a reverse look up regex. We like this method because it will remove the last comma regardless of what is after the comma. Sometimes there could be trailing html or hidden newlines. This regex will find the last occurrence of the comma and replace it.
We noticed a CSS based solution in the Saxotech documentation provided by @staceymosier in the comments here: https://docs.saxotech.com/display/Onl/NewsItemTaxonomyWordItem.pbo using the NewsItemTaxonomyWords.pbo and NewsItemTaxonomyWordsItem.pbo files. This is what was provided on that page:
Then in your CSS:
Line 1 contains the escaped unicode for comma and line 2 contains Last-child, clear the content. It is also noted that IE before IE9 doesn’t support :last-child, but it does support :first-child, so that’s a better option. Meaning, you can place the ‘,’ before the <%Name%> variable, and remove the first comma instead of the last.
While we prefer the regex especially in cases where we are creating JSON or something that can’t be modified via CSS, this is a really nice way to solve the problem client-side. Thanks @staceymosier!
Share with us how you have solved this in your code.
Latest posts by Stacey Jenkins (see all)
- Display your youtube playlists or channels on your site directly from Youtube - June 7, 2014
- You say you want PHP SOSE examples? - January 14, 2014
- Building a better UX on CCE submit forms - December 5, 2013