Coldfusion String removes everything after the last comma

I have some dynamic data that give me something like this:

123,151425,15641,12 

I need to delete everything after the last comma so that 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> 
+5
source share
3 answers

This should do what you want.

 <cfif ListLen(OldString) GT 1> <cfset NewString = ListDeleteAt(OldString,ListLen(OldString))> </cfif> 

If you need more flexibility in how many elements chop off the end, ListDeleteRight from CFLib.org would be helpful.

 <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 ( shaun.ambrose@arcorsys.com ) * @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> 

Using:

 ListDeleteRight(list, numElements [, delimiter]) 

Example:

 <cfset NewString = ListDeleteRight(OldString,1)> 
+1
source

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

 ListDeleteAt(list, position [, delimiters ]) 
+8
source

Another solution:

Here I use the java string lastIndexOf functions to return the last comma index and the substring function to extract from the beginning of the line to the position of the last comma.

  <cffunction name="stripAfter" returntype="String" output="false"> <cfargument name="input" type="string" required="true"> <cfargument name="delimiter" type="string" required="false" default=","> <cfset lastCommaIndex = input.lastIndexOf(",")> <cfif lastCommaIndex EQ -1> <cfreturn input> </cfif> <cfreturn input.substring(0, lastCommaIndex)> </cffunction> <cfoutput> #stripAfter(OldString)# </cfoutput><br/> 
-1
source

Source: https://habr.com/ru/post/1202706/


All Articles