Skip to main content
Ben Nadel at Dan Wilson's 2011 (North Carolina) with: Nick James Wilson
Ben Nadel at Dan Wilson's 2011 (North Carolina) with: Nick James Wilson

Referencing String Characters Using Array-Notation In Lucee CFML 5.3.5.92

By on
Tags:

Over the weekend, I was reading through the Learn Modern ColdFusion <CFML> in 100 Minutes book by Ortus Solutions when I came across their section on Character Extraction. In that section, they mention that - in Lucee CFML - you can access the characters of a String using Array-notation. Since I don't remember ever seeing this feature before, I wanted to quickly try it out for myself so as to try and burn the concept into my brain.

Like all ColdFusion arrays, lists, queries, etc, treating a String like an array of characters starts at index 1:

<cfscript>
	
	value = "Jello";

	// A string can be accessed like an array of characters (1-based, of course).
	echo( value[ 1 ] & "-" );
	echo( value[ 2 ] & "-" );
	echo( value[ 3 ] & "-" );
	echo( value[ 4 ] & "-" );
	echo( value[ 5 ] & "-" );

	// Going out-of-bounds will throw an error; but, we can use our Elvis-operator to
	// provide a fall-back value for a null index.
	echo( value[ 6 ] ?: "!" );

</cfscript>

As you can see, we are treating String value as a character Array. And, when we run this Lucee CFML code, we get the following output:

J-e-l-l-o-!

Interesting! To be honest, I don't have a lot of use-cases in which I have to iterate over the characters in a string in ColdFusion. But, it's good to know that this feature exists should the need arise.

ASIDE: I tried to use negative array indexing, like value[ -1 ], to grab the last character in the string. This does not work.

Also, attempting to use .map() on the String does not throw an error; but, it does not iterate over the string characters. It appears to perform a single iteration with the String value as the one iteration item.

Want to use code from this post? Check out the license.

Reader Comments

15,643 Comments

@Charles,

Yes, that's exactly right. But here's my emotional struggle: by the time you are going to start pulling in other methods like len(), I would probably just revert back to a simpler: value.right( 1 ). That's why I think this is "interesting"; but, I'm not sure how often I would actually use it.

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel