How do I remove a trailing comma from a string in ColdFusion?
Check the rightmost char - if it's a comma, set the string to a substring of the original, with length -1.
Trimming the string ensures that spaces after the trailing comma don't interfere with this method.
<cfset myStr = "hello, goodbye,">
<cfset myStr = trim(myStr)>
<cfif right(myStr, 1) is ",">
<cfset myStr = left(myStr, len(myStr)-1)>
</cfif>
To remove a trailing comma (if it exists):
REReplace(list, ",$", "")
To strip one or more trailing commas:
REReplace(list, ",+$", "")
To add onto Patrick's answer. To replace one or more commas at the end use the following: reReplace(myString, ",+$", "", "all")
Example Below
<cfset myString = "This is the string, with training commas,,,">
<cfset onlyTheLastTrailingComma = reReplace(myString, ",$", "", "all")>
<cfset allTrailingCommas = reReplace(myString, ",+$", "", "all")>
<cfoutput>#onlyTheLastTrailingComma#<br />#allTrailingCommas#</cfoutput>
This is probably more of a performance hit than Regex'ing a list, but sometimes when I end up filtering/fixing dirty data, I convert it to an array and then convert it back into a list.
<cfset someVariable = arrayToList(listToArray(someVariable, ","), ",")>
It's cheating, but it works ;-)
Also easy:
<cfset CleanList = ListChangeDelims(DirtyList, ",", ",")>
Explanation: This takes advantage of the fact that CF list functions ignore empty elements. ListChangeDelims()
consequently strips off that last "element".
@Tomalak
if i could vote you up i would. that is an excellent suggestion and cool trick.
Remove "," from Both Sides, Just the Right Side, or Just the Left Side
<cfset theFunnyList = ",!@2ed32,a,b,c,d,%442,d,a">
Replace Funny Characters and Separate with Comma
<cfset theList = rereplace(theFunnyList, "[^A-Za-z0-9]+", ",", "all")>
<cfset theList = trim(theList)>
<cfif left(theList, 1) is "," and right(theList, 1) is ",">
<cfset theList = right(theList, len(theList)-1)>
<cfset theList = left(theList, len(theList)-1)>
<cfelseif right(theList, 1) is ",">
<cfset theList = left(theList, len(theList)-1)>
<cfelseif left(theList, 1) is ",">
<cfset theList = right(theList, len(theList)-1)>
</cfif>
Sort List (Numeric to A-Z) ASCending
<cfoutput> #ListSort("#theList#", "text", "ASC", ",;")# </cfoutput>