Writing User-Defined Functions
If you have a bit of familiarity with ColdFusion already, you may know that new with ColdFusion 5 is the ability to create user-defined functions. But you may not know yet how to do it. In this article, we will create our own user-defined function that you can use to delight your friends. Along the way, you will learn several existing string functions, such as Find, FindNoCase, Reverse, LCase, and a couple of regular expression functions.
User-defined functions have this syntax in ColdFusion, shown in Listing 1.
Listing 1: User-Defined Function Syntax
<cfscript> function functionName( [paramName1[, paramname2...]] ) { CFScript Statements } </cfscript>
We will write a self-posting form that allows a user to enter a text sting. We will then write a user-defined function called isPalindrome(). A palindrome is a word that reads the same backward or forward. Therefore, this function will read the passed string, reverse it, and check to see if the reversed string is equivalent to the original string. If it is, the string is a palindrome. We then call our custom function just like we would any other, which will tell the user whether his string is a palindrome.
First, let's write the function. In order to create this function, we can make good use of the existing functions Reverse, which reverses a string, and Find, which finds a substring in a given string.
So that you can see how these are working, let's quickly look at them in their own right.
Reverse()
The Reverse() function returns the passed string with its characters in reverse order. Therefore, the result of this code
<cfoutput>#Reverse("Alison Brown")#</cfoutput>
is this:
nworB nosilA