Replace last comma or use ColdFusion

What is the best way to convert an array of values ​​to ColdFusion

[ Fed Jones, John Smith, George King, Wilma Abby] 

and to the list where the last comma is or

 Fed Jones, John Smith, George King or Wilma Abby 

I thought REReplace might work, but have not yet found the correct expression.

+4
source share
3 answers

If you have an array, combining the last element with an ArrayToList is the easiest way (according to Henry's answer ).

If you got it as a string, using reereplace is a valid method and will work as follows:

 <cfset Names = rereplace( Names , ',(?=[^,]+$)' , ' or ' ) /> 

Which says it matches a comma, and then checks (without matching) that there are no more commas until the end of the line (which, of course, will only apply to the last comma, and therefore it will be replaced).

+12
source

At first it would be easier to manipulate at the array level before moving on to the list.

 names = ["Fed Jones", "John Smith", "George King", "Wilma Abby"]; lastIndex = arrayLen(names); last = names[lastIndex]; arrayDeleteAt(names, lastIndex); result = arrayToList(names, ", ") & " or " & last; // result == "Fed Jones, John Smith, George King or Wilma Abby" 
+5
source

Another option is to work with a list / string using the listLast and JAVA lastIndexOf () method of the resulting string.

 <cfscript> names = ["Fed Jones", "John Smith", "George King", "Wilma Abby"]; result = arraytoList(names,', '); last = listLast(result); result = listLen(result) gt 1 ? mid(result, 1, result.lastIndexOf(',')) & ' or' & last : result; </cfscript> <cfoutput>#result#</cfoutput> 

Result:

Fed Jones, John Smith, George King or Wilma Abby

+2
source

All Articles