Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return partial string in ColdFusion

Tags:

coldfusion

Lets say I have a string The big brown fox jumped<br> over the fence. How could I specify that I want to keep only the characters that are before the <br> tag, stripping out the rest?

like image 432
The Muffin Man Avatar asked Jan 27 '11 21:01

The Muffin Man


Video Answer


2 Answers

I use something similar, don't know if it's more efficient.

<cfset string = "The big brown fox jumped<br> over the fence.">

<cfset firstPiece = listGetAt(string, 1, "<br>")>
<cfoutput>#firstPiece#</cfoutput>

I like it because I determine the output prior to output rather than on output. But orangepips is nice because you could tailor your output based on the context..

EDIT

As pointed out in the comments the above code indeed produces "The" because of the way CF treats each character as a delimiter.

But <cfset firstPiece = listGetAt(string, 1, "<") produces "The big brown fox jumped".

From the CF Documentation

Delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter.

like image 120
Ofeargall Avatar answered Nov 01 '22 12:11

Ofeargall


If you don't mind dropping down to a bit of the old java underlying CF... AColdFusion string is actually a java string. Java's split uses a regex, which at it's simplest can just be the string you want to split on. So unlike listToArray (which was extended in cf9 to allow multi-character splits, by the way), it is by definition multi-character. And since it's a regex, if you want it case insensitive, that too can be easily accomplished.

So given your string:

<cfset variables.myString = "The big brown fox jumped<br> over the fence." />
<cfset variables.myStringArray = variables.myString.split("(<[bB][Rr]>)",2) />
<cfset variables.myString = variables.myStringArray[1] />

variables.myStringArray will contain an array with at most 2 elements, the part before the first <br>, and the part after the first <br> (the second parameter to split, the 2, says to only split into 2 parts, at the most) occurrence, which will leave any <br>'s in the second part of your string intact.

like image 20
Mark Avatar answered Nov 01 '22 12:11

Mark