Remove the last occurrence of a character in a string
Just a quick post in response to a question my collegue Simon Bingham, has just asked me. He has a string, and needs to remove the last occurrence of a specific character from it. There are several solutions (some involving loops!), however by taking advantage of the Java String methods we can do it quite easily.
Here's a quick example of 3 different ways to accomplish the same thing.
<!--- original string that we want to remove the last comma from ---> <cfset mystring = "The cat, in the hat, sat on the mat, fancy that!" /> <cfoutput> <!--- using ReReplace function with a backreference (thanks Paul Klinkenberg) ---> #ReReplace(mystring, '(.*),', '\1')#<br /> <!--- using CFML Reverse function and the replaceFirst Java String method ---> #Reverse(Reverse(mystring).replaceFirst(',',''))#<br /> <!--- using CFML RemoveChars function and the lastIndexOf Java String method ---> #RemoveChars(mystring,mystring.lastIndexOf(',')+1,1)#<br /> </cfoutput>
All of the above techniques will return:
The cat, in the hat, sat on the mat fancy that!
Of course, now he's changed his mind and wants to replace it, so with a quick mod we can get the desired result.
<!--- original string that we want to replace the last comma from with an & ---> <cfset mystring = "The cat, in the hat, sat on the mat, fancy that!" /> <cfoutput> <!--- using ReReplace function with a backreference (thanks Paul Klinkenberg) ---> #ReReplace(mystring, '(.*),', '\1 &')#<br /> <!--- using CFML Reverse function and the replaceFirst Java String method ---> #Reverse(Reverse(mystring).replaceFirst(',',';pma& '))# </cfoutput>
We now get:
The cat, in the hat, sat on the mat & fancy that!
- Posted in:
- ColdFusion


Comment by Simon Bingham – June 03, 2009
My code is now doing what I want it to do.
<cfset foo=REReplace( foo, "[^..]", "" ) />
<cfset foo=Reverse( Reverse( foo ).replaceFirst( ',', ' ;pma& ' ) ) />
The code converts a list from (for example):
", Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday"
to:
"Monday, Tuesday, Wednesday, Thursday, Friday, Saturday & Sunday"
Very handy!
Comment by Simon Bingham – June 03, 2009
ReReplaceNoCase( mystring, "^, ", "" )
Comment by John Whish – June 03, 2009
Because regEx is greedy, it takes as much chars as possible into .* before matching the (last occurence of the) character.
Comment by Paul Klinkenberg – June 03, 2009
Comment by John Whish – June 04, 2009
Comment by Ryan v. – July 22, 2009
This made my work in minutes
Thanks!
Comment by sureen – November 02, 2009
Comment by Michael B. – February 16, 2010