I have some dynamic data that gives me something like this:
123,151425,15641,12
I need to remove everything after the very last comma so it displays:
123,151425,15641
I have this code, but it only removes the last comma. I need to remove the comma and everything after it.
<cfset NewString = ReReplace(OldString, '(.*),', '\1')>
<cfoutput>
   #NewString#
</cfoutput>
                Use ListDeleteAt(), using ListLen() to get the position of the last element.
ListDeleteAt(list, position [, delimiters ])
                        This should do what you want.
<cfif ListLen(OldString) GT 1>
  <cfset NewString = ListDeleteAt(OldString,ListLen(OldString))>
</cfif>
If you want some more flexibility in how many elements to chop off the end, ListDeleteRight from CFLib.org would be useful.
<cfscript>
/**
 * Deletes the n rightmost elements from the specified list.
 * Modified by RCamden
 * 
 * @param list      The list to modify. 
 * @param numElements      The number of elements to delete. 
 * @param delimiter      The delimiter to use. Defaults to a comma. 
 * @return Returns a string. 
 * @author Shaun Ambrose ([email protected]) 
 * @version 1, April 24, 2002 
 */
function ListDeleteRight(list, numElements) {
    var i=0;
    var delimiter=",";
    if (Arraylen(arguments) gt 2) {
        delimiter=arguments[3];
    }
    if (numElements gt ListLen(list, delimiter)) return "";
    for (i=1; i lte numElements; i=i+1) {
        list=listDeleteAt(list, listLen(list, delimiter), delimiter);
    }
    return list;
}
</cfscript>
Usage:
ListDeleteRight(list, numElements [, delimiter])
Example:
<cfset NewString = ListDeleteRight(OldString,1)>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With