REReplace
There are four ColdFusion regular expression functions, and they perform very complex string manipulation. They all begin with "RE." REReplace performs a case-sensitive search of a given string, finds a regular expression within string and replaces it with substring in the given scope. Here is the structure:
REReplace(string, reg_expression, substring [, scope ])
We want to take the string passed as FORM.MyString, find all of the spaces in that string, and replace each space with an empty string. We want to do this for every instance of a space in the string, not just the first one we find. So, ours is written this way:
mystring = REReplace(form.MyString," ","","ALL");
We set the variable MyString to the result of performing the REReplace. If we used <cfoutput> or <cfdump> at this point to view the contents of the variable MyString, all spaces would have been removed.
Now we can plug this into our script, send it a value with spaces, and see if it works. The bold code in Listing 4 shows where we have made updates.
Listing 4: Updated Palindrome.cfm
<html> <head> <title>Updated Palindrome</title> </head> <body> <cfscript> function isPalindrome(string){ mystring = REReplace(form.MyString," ","","ALL"); RevString = Reverse(mystring); { if (FindNoCase(RevString, MyString) is 1) theResult = "<b>#form.MyString#</b> is a palindrome!"; else theResult = "<b>#form.MyString#</b> is not a palindrome :("; } return theResult; } </cfscript> <cfif isDefined("FORM.MyString")> <cfoutput>#isPalindrome(FORM.MyString)#</cfoutput> </cfif> <br> <br> Please type a string, and I will tell you if it is a palindrome or not: <br> <form action="UDFnocase.cfm" method="post" name="MyString"> <input type="text" name="MyString" size="20"><br> <input type="submit" name="Submit"> </form> </body> </html>
There are a number of changes, but our application is much improved. Here's what we did:
Used the regular expression function REReplace to strip out any spaces between words
Read the string as not case-sensitive
Instead of the generic your string, displayed the string that we checked
Now we get better results.
NOTE
Variables created in a user-defined function are not visible outside the function, unless they are explicitly returned.
There is still an important flaw with our isPalindrome() function. If the function were passed this string
Go hang a salami. I'm a lasagna hog?
it would return false, even though it is a palindrome. That's because of the period, the apostrophe, and the question mark. In order to ignore these special characters, you can learn another string function: ReplaceList().