Gene R
Gene R

Reputation: 1565

ColdFusion and trailing comma

How do I remove a trailing comma from a string in ColdFusion?

Upvotes: 12

Views: 12055

Answers (6)

richard
richard

Reputation: 11

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>

Upvotes: 1

Tomalak
Tomalak

Reputation: 338108

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".

Upvotes: 15

Phydiux
Phydiux

Reputation: 144

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 ;-)

Upvotes: 4

Jason
Jason

Reputation: 276

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>

Upvotes: 2

Patrick McElhaney
Patrick McElhaney

Reputation: 59271

To remove a trailing comma (if it exists):

REReplace(list, ",$", "")

To strip one or more trailing commas:

REReplace(list, ",+$", "")

Upvotes: 25

ConroyP
ConroyP

Reputation: 41886

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>

Upvotes: 5

Related Questions