Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coldfusion String remove everything after last comma

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>
like image 584
Katherine Pacheco Avatar asked Sep 16 '14 18:09

Katherine Pacheco


2 Answers

Use ListDeleteAt(), using ListLen() to get the position of the last element.

ListDeleteAt(list, position [, delimiters ])
like image 82
Adrian J. Moreno Avatar answered Oct 16 '22 09:10

Adrian J. Moreno


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)>
like image 33
Fish Below the Ice Avatar answered Oct 16 '22 08:10

Fish Below the Ice