Coldfusion: How to split a string into a set of variables

Jack Pilowsky picture Jack Pilowsky · May 15, 2014 · Viewed 37.6k times · Source

I'm trying to teach myself ColdFusion.

I have a string coming in from the database in this format:

domain.com
<br/>
www.facebook.com/facebookpage
<br/>
http://instagram.com/instagrampage

It is all coming from #getRacer.txtDescription#. The format of this text will always be the same.

I need to split it into 3 variables. I tried this (derived from the example on the adobe website)

<h3>ListToArray Example</h3>
<cfset myList = ValueList(getRacer.txtDescription)>
<p>My list is a list with <cfoutput>#ListLen(myList)#</cfoutput> elements.
<cfset myArrayList = ListToArray(myList,'<br/>')>
<p>My array list is an array with 
<cfoutput>#ArrayLen(myArrayList)#</cfoutput> elements.

I somehow ended up with 11 items in the array.

Thank you

Answer

Gaurav S picture Gaurav S · May 15, 2014

This should work.

<cfset TestSTring = "domain.com<br/>www.facebook.com/facebookpage<br/>http://instagram.com/instagrampage">

<cfset a = TestString.Split("<br/>")>

The reason ListtoArray is displaying 11 items is because ColdFusion treats each character in the delimiter string (<br/>) as a separate delimiter

Based on @Leigh's comment updating my answer to ensure people should learn the Coldfusion APIs rather than fiddling with Java functions, <cfset a = ListToArray(TestString, "<br/>", false, true)> will also work. Thanks Leigh.

Note: The false at the end is for the includeEmptyFields flag and the true is for the multiCharacterDelimiter flag. See the docs.