Finding and replacing text in a string (formatted as list)

So I’m pulling a column from a database that has a similar structure to this:


animal_type=cows;beverage_type=soda;food_type=pizza

So obviously I can easily convert this to a list and loop over it to find out if what I want exists and change it if so or append it if not. Problem with that is I’m converting to a list, then looking, then changing and then converting back to a string. Too many ‘thens’ in that sentence for me to think that’s the right answer. :slight_smile:

I’m feeling like findNoCase() is what I SHOULD be using, and I’ve played with it and get a count in the string where the value i’m looking for is at, but I’m not sure what I can do with that value.

So for instance:


#FindNoCase('food_type', string)#

returns ‘37’ but what can I do to change the value after the equal sign?

I’m assuming the basic plan would go something like this:


<cfset string = "animal_type=cows;beverage_type=soda;food_type=pizza">

<cfset location = findNoCase('animal_type', string)>
<cfif location EQ 0>
	<!--- append the value to the existing string and return --->
<cfelse>
	<!--- change the value and return --->
</cfif>

I can’t say I’ve had this situation come up before and am a little lost, thanks for any help.

Okay, THINK I have this figured out…*for anyone else that might run into this issue (anyone that thinks this is a bad solution, PLEASE speak up).


<!--- initial string --->
<cfset string = "animal_type=cows;beverage_type=soda;food_type=pizza;">
<!--- get the position where target begins --->
<cfset start = findNoCase('beverage_type', string)>
<!--- find the position of the end of the target (my case a semicolon) starting at the beginning of the target ---> 
<cfset end = find(';',string,start)>
<!--- subtract the end point from the beginning point to get length --->
<cfset length = end-start>
<!--- use mid() to get target --->
<cfset result = Mid(string,start,length) & ";">
<!--- ReReplaceNoCase() to remove target from string --->
<cfset cleaned = ReReplaceNoCase(string,result,'')>
<!--- add new value to end of string --->
<cfset new = cleaned_preferences & 'beverage_type=water;'>

Whether I’m saving any overhead by doing it this way instead of converting list to a array of structs, I have no idea.