This blog has moved here: woorkup.com | FOLLOW ME ON TWITTER @woork
Tuesday, January 8, 2008

Split text string using Coldfusion

This tutorial explains how to split an input text string (with some values comma separed) using Coldfusion.


The code is very simple (you can use insted of input string tag_source equal to 'database, mysql, tutorial, how-to' another value such as a #FORM# variable):

<!--- String to split --->
<cfset tag_source = 'database, mysql, tutorial, how-to'>

<cfset comma_pos = -1>
<cfset index = 1>
<cfset tag_array = ArrayNew(1)>
<cfloop condition= "comma_pos NEQ 0 AND len(tag_source) GT 0">
<cfset comma_pos = #find(",", tag_source)#>
<cfif comma_pos NEQ 0>
<cfif comma_pos EQ 1>
<cfset tag_source_n = #left(tag_source, comma_pos)#>
<cfelse>
<cfset tag_source_n = #left(tag_source, comma_pos-1)#>
</cfif>
<cfset tag_source = #removechars(tag_source, 1, comma_pos)#>
<cfset tagArray[index] = trim(tag_source_n)>
<cfelseif comma_pos EQ 0 AND len(tag_source) GT 0>
<cfset tagArray[index] = trim(tag_source)>
</cfif>
<cfset index = index+1>
</cfloop>

<!--- Do something with splittet tags --->
<cfloop from="1" to="#arrayLen(tagArray)#" index="i">
<cfquery name="insertTag" datasource="aigers">
INSERT INTO TAG (tag)
VALUES (
'#tagArray[i]#'
)
</cfquery> </cfloop>

blog comments powered by Disqus
Anonymous said...

Or maybe just set tag_array = ListToArray(tag_source)?

Or am I missing something?

Eric said...

Or
myArr=myString.split(-1)

Take care with this method that return an Java array and not a Coldfusion array but that is more simple and very powerfull. For example it is possible to get array from string like "1,2,3,4," (see coma at the end) and you can use Regular Expressions.
see javadoc http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#split(java.lang.String,%20int)

Aubweb said...

Thank you Eric
very useful especially with the findoneof !

Pranav Prakash said...

Thanks Eric. This saved a considerable amount of time in my case.

  • Twitter Follow woork on Twitter
  • RSS Feed Subscribe to stay up to date
  • Podcast Coming soon...
  • 0 delicious lovers save
Share your links. Do you want to suggest any interesting link about web design or tech news? Submit your link.
Submit a News