Often when building a list of some sort, an unnecessary delimiter ends up tacked onto the end of the string. While it’s certainly ok to keep up with the loop that is building the list, and if it is the last loop to not add the list delimiter. However, often that creates extra code that could be eliminated if there were a simple way to just build the string, add the delimiter to the end within the loop, and once complete remove the last character from the completed list. This can be easily accomplished with Coldfusion’s removeChars() function. Let’s take an example of building a url with a set of parameters.
Build a URL
<cfset variables.url = "http://www.afakedomain.com?">
<cfset variables.urlObj = {} />
<cfset variables.urlObj.1 = {} />
<cfset variables.urlObj.2 = {} />
<cfset variables.urlObj.3 = {} />
<cfset variables.urlObj.1.key = "paramOne" />
<cfset variables.urlObj.1.value = "paramOneValue" />
<cfset variables.urlObj.2.key = "paramTwo" />
<cfset variables.urlObj.2.value = "paramTwoValue" />
<cfset variables.urlObj.3.key = "paramThree" />
<cfset variables.urlObj.3.value = "paramThreeValue" />
<cfloop collection="#variables.urlObj#" item="variables.i">
<cfset variables.url = variables.url & variables.urlObj[variables.i].key & "=" & variables.urlObj[variables.i].value & "&" />
</cfloop>
As this code currently stands the resulting url will be:
http://www.afakedomain.com?paramThree=paramThreeValue¶mTwo=paramTwoValue¶mOne=paramOneValue&
Notice the ampersand at the end of the url. This is the result of creating a delimited list via a loop. Depending on how you build your list, a delimiter will always exist at the beginning or end of the completed list. In the past I’ve always handled this by checking if the loop index was the last index, and if so did not add the delimiter. However, the last time I ran into this I figured that it was time to build a better way of doing this, or dig into the docs and look for a better way.
Searching the docs yielded the ‘removeChars()’ method. The method signature takes three parameters – the string to remove characters from, where to start removing characters, and how many characters to remove. So to make this work with our URL we need to remove the last character. To do this we can add the following line of code immediately after the loop completes.
<cfset variables.url = removeChars(variables.url, len(variables.url), 1) />
Now if the variables.url var is dumped we get
http://www.afakedomain.com?paramThree=paramThreeValue¶mTwo=paramTwoValue¶mOne=paramOneValue
The ampersand (or last character) was removed. Hope this helps.
At Monserrate Monastery in Bogotá, Colombia.