James T
James T

Reputation: 3320

Coldfusion string::split() issue

I have the following code

<cffunction name="getObjTag" returnType="string" output="false">
    <cfargument name="obj" Type="string" required="true">
    <cfargument name="tagname" Type="string" required="true">
    <cfreturn obj.split("<" & tagname.toUpperCase() & ">")[2]>
</cffunction>

Which results in the following error

Invalid CFML construct found on line 96 at column 63.

ColdFusion was looking at the following text:

[

The CFML compiler was processing:

A cfreturn tag beginning on line 96, column 10.
A cfreturn tag beginning on line 96, column 10.

Why is this? This happens on compile, not run.

Upvotes: 3

Views: 7586

Answers (2)

Todd Sharp
Todd Sharp

Reputation: 3355

CF 9 added the ability to access the results of the split as an array directly from the function call. The following works as expected on my local install of 9.0.1:

<cfset foo = "this is a string" />
<cfdump var="#foo.split(" ")[1]#" />

The dump shows 'this' in this example.

Upvotes: 3

Mark
Mark

Reputation: 2562

CF can't access the results of the split as an array directly from the function call. You need an intermediate variable.

<cfset var tmpArray = arrayNew(1)/>
<cfset tmpArray = arguments.obj.split("<" & arguments.tagname.toUpperCase() & ">")/>
<cfif arrayLen(tmpArray) gt 1>
   <cfreturn tmpArray[2]/>
<cfelse>
   <cfreturn ""/>
</cfif>

You also need to watch your indexes. Although the java array underneath is 0 index'ed, using coldfusion to get at it makes it indexed by 1.

Upvotes: 2

Related Questions