Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace last comma with or using ColdFusion

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

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

and to a list where the last comma is an or

Fed Jones, John Smith, George King or Wilma Abby

I thought REReplace might work but haven't found the right expression yet.

like image 842
Aaron Avatar asked Dec 12 '12 00:12

Aaron


3 Answers

If you've got an array, combining the last element with an ArrayToList is the simplest way (as per Henry's answer).

If you've got it as a string, using rereplace is a valid method, and would work like so:

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

Which says match a comma, then check (without matching) that there are no more commas until the end of the string (which of course will only apply for the last comma, and it will thus be replaced).

like image 156
Peter Boughton Avatar answered Oct 16 '22 11:10

Peter Boughton


It'd be easier to manipulate in the array level first, before converting into a 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"
like image 28
Henry Avatar answered Oct 16 '22 13:10

Henry


Another option is to work with a list / string using listLast and the JAVA lastIndexOf() method of the result 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

like image 30
genericHCU Avatar answered Oct 16 '22 12:10

genericHCU