How to split a comma delimited string into an array in cfscript
Is there an easy way to split a comma开发者_StackOverflow delimited string into an array using cfscript?
Something similar to the following JavaScript:
var a = "a,b,c".split(",");
var a = ListToArray("a,b,c,d,e,f");
https://cfdocs.org/listtoarray
Your two main options are listToArray(myList) and the java method myList.split(), as noted in previous answers and comments. There are some things to note though.
- By default ColdFusion list functions ignore empty list items.
- As of ColdFusion version 8, listToArray takes an optional third argument, includeEmptyFields, which is a boolean controlling that behavior, defaulting to false.
For example:
listToArray("asdf,,,qwer,tyui") is ["asdf", "qwer", "tyui"]
listToArray("asdf,,,qwer,tyui", ",", true) is ["asdf", "", "", "qwer", "tyui"]
Re java split:
Like other java functionality that pokes up through the ColdFusion layer, this is undocumented and unsupported
In Adobe ColdFusion 8, 9, and 10, but not in Railo, this is a syntax error:
a = "asdf,,,qwer,tyui".split(",")
But this works:
s = "asdf,,,qwer,tyui";
a = s.split(",");
As far as I can see, Adobe ColdFusion treats the result of .split() like a ColdFusion array:
- CFDumps show it as an array
- It's 1-based
- You can use arrayLen on it
- You can modify its elements in ColdFusion
- There may be other behaviors I didn't check that aren't like a CF array, but as above, it's unsupported
In Railo:
- Debug dumps show it as Native Array (java.lang.String[])
- The other statements about its very array-like behavior are still true
That's in contrast to real java arrays, created with createObject("java", "java.util.ArrayList").
NOTE: That's only partly correct; see edit below.
- For instance, in Adobe ColdFusion, elements of a java ArrayList can't be modified directly with CFML
- In general, Railo handles java arrays more like ColdFusion ones than ACF
Edit: Thanks Leigh, I stand corrected, I should stick to what I know, which is CF way more than java.
I was reacting to the comment saying that the result of .split() "is not a ColdFusion array, but a native Java array. You won't be able to modify it via CF", which is not the case in my experience. My attempt to clarify that by being more specific was ill-informed and unnecessary.
精彩评论