CF_IM07

advertisement
Chapter 7
Built-In Functions
Overview
Chapter 7 covers many of the frequently used built-in functions that may be found in
ColdFusion. String manipulation functions such as those used to trim strings, justify strings,
convert string case, wrap strings, encrypt/decrypt strings, extract substrings, and finding strings
within other strings are discussed in great detail including example uses of each one. Syntax for
the IsNumeric and IsDefined Boolean functions are described and demonstrated within this
chapter. Descriptions of many widely used mathematical functions are presented as well as
example uses. Date and time functions described in this section will be helpful not only for
formatting data, but also when it is necessary to perform mathematics with dates.
Through the use of the Evaluate function, students will be able to create more generic forms
which will aid in the creation of reusable forms regardless of database structure. Lastly, a close
look at using system functions for working with files and directories will facilitate the creation of
variables for path and file names to enable ease of moving web applications to different locations
on a server.
Teaching Tips and Strategies
Quite often learning built-in functions is difficult because students may not be able to visualize
an instance where the use of that function would come in handy. Have a brain-storming session
as a group to try to find a “real world” situation for each of the functions. For example: using
the Replace function to only show the last four digits of a credit card number.
Lecture Notes
I. String Manipulation
A. Trimming Strings
1. Ltrim – trims leading spaces
2. Rtrim – trims trailing spaces
3. Trim – trims leading and trailing spaces
B. Justifying Strings
1. Ljustify – left aligns a string by padding spaces at the end of the string
2. Rjustify – right aligns a string by padding spaces at the beginning of the string
3. Cjustify – centers a string by padding spaces before and after the string
C. Changing String Case
1. Lcase – converts a string to lower case characters
2. Ucase – converts a string to upper case characters
D. Wrapping Strings
1. Wrap – limits the number of characters per line
E. String Encryption and Decryption
ColdFusion
Chapter 7: Built-In Functions
1. Encrypt – uses a symmetric key-based algorithm to encrypt a string
2. Decrypt – decrypts the string using the same key that was used to encrypt it
F. Extracting Substrings
1. Len – returns the number of characters in a string
2. Left – returns the specified number of characters from the left
3. Right – returns the specified number of characters from the right
4. Mid – returns the specified number of characters from anywhere in the string
5. RemoveChars – returns a string with the specified number of characters
removed from it
G. Searching and Replacing Strings
1. Find – case sensitive search for a substring within a string; returns the position
of the first occurrence of the substring or 0 if it is not found
2. FindNoCase – case insensitive search for a substring within a string; returns
the position of the first occurrence of the substring or 0 if it is not found
3. FindOneOf – returns the position of the first occurrence of any characters
specified or 0 if not found
4. Replace – case sensitive replacement of occurrences of a string within
another; returns the new string after substitution
5. ReplaceNoCase – case insensitive replacement of occurrences of a string
within another; returns the new string after substitution
II. Decision or Boolean Functions – return True or False
A. IsNumeric – returns True if string can be converted to a number
B. IsDefined – returns True if the named variable exists
III. Mathematical Functions
A. Min – returns the smaller of two numbers
B. Max – returns the larger of two numbers
C. Round – rounds a number to the closest integer
D. Sqr – returns the square root of a number
E. Abs – returns the absolute value of a number
F. Rand – returns a random number in the range 0 to 1
G. Randrange – returns a random number within the range specified
H. NumberFormat – formats the display of numbers using a mask
IV. Date and Time Functions
A. CreateDate and CreateDateTime – return a valid data/time object
B. CreateODBCDate and CreateODBCDateTime – return a valid date/time object in
ODBC date format
C. DateFormat – returns the data/time formatted as specified in the mask
D. DatePart – returns part of a date as an integer such as year
E. DateAdd – returns the date to which a period has been added
F. DateDiff – returns the number of intervals in units by which the dates differ
G. Functions to extract parts of dates
1. Day
2. Month
3. Year
4. Quarter
H. DaysInYear – returns the number of days in a year
CF_IM07-2
ColdFusion
Chapter 7: Built-In Functions
DaysInMonth – returns the number of days in the month
DayOfWeek – returns the numeric day of the week
DayOfYear – returns the numeric day of the year
DayOfWeekAsString – converts the day of week number into the name of the day of
the week
M. MonthAsString – converts the month number into the name of the month
N. IsDate – returns True if the string is a valid date
O. IsLeapYear – returns True if the year is a leap year
V. Evaluation of Expressions
A. Evaluate – evaluates arguments and returns the result of evaluating the last argument
VI. System Functions – to access files and directories on the server
A. ExpandPath – converts a relative directory reference to an absolute path
B. GetDirectoryFromPath – extracts the directory from a fully specified path
C. GetFileFromPath – extracts the filename from a fully specified path
D. DirectoryExists – returns Yes if the directory specified exists
E. FileExists – returns Yes if the file specified exists
F. GetBaseTemplatePath – returns the absolute path of an applications base page
I.
J.
K.
L.
CF_IM07-3
ColdFusion
Chapter 7: Built-In Functions
Review Questions
Answers:
1.
Trim functions remove extra spaces on the left, right, or both sides of a string and return the
string without these extra spaces. Trimming is useful when you want to compare strings
with one another. Ltrim: trims leading spaces, i.e. spaces from the beginning of the string.
Rtrim: trims the trailing spaces, i.e. spaces from the end of the string. Trim: trims the
leading and trailing spaces, i.e. spaces from the beginning and end of the string.
2.
Justification functions help to display a string in an appropriate location within a field wider
than the length of the string. Ljustify – left aligns a string within a field of a specified length.
It does this by padding spaces after the specified string. Rjustify – right aligns a string
within a field of a specified length. It does this by padding spaces before the specified string.
Cjustify – centers a string within a field of a specified length. It does this by padding spaces
before and after the specified string.
3.
Convert the case of a lower-case string to make it uppercase or of an upper-case string to
make it lowercase.
Uses:
 case sensitive comparisons of strings
 insert strings with consistent case into a database
 Display information in a consistent manner, e.g. First and last name with first
character capitalized no matter how it is entered by the user
 Lcase converts a string to lower case; Ucase converts a string to upper case
4.




Extracting the last 4 digits of a Social Security number
Capitalizing the first character of a word
Extracting area code from a telephone number, e.g. (408) 725 3655. Here we would
extract 3 characters, starting from the 2nd character.
Left and Right– these functions return the specified number of characters from the left or
right of the string respectively. They take two parameters: the string from which to
extract these characters and the number of characters to extract.
5.
Searching strings can be useful to find a substring within a string. For example, we may
want to search and remove all “()” and “-“ in a telephone number so that it is completely
numeric.
6.
Min returns the smaller value of two numbers. Max returns the larger value of two numbers.
Round – this function rounds a number to the closest integer.
7.
#numberformat(num, "$____.__")#
CF_IM07-4
ColdFusion
8.
Chapter 7: Built-In Functions
Datepart returns part of a date as an integer.
#DatePart("yyyy", thisDate)# gives the year output 2002.
9.
DateAdd, DateDiff – DateAdd returns the date to which a period has been added.
Parameters are Datepart – part of date to add, number of units of datepart to add to date (if
positive) or subtract from date (if negative), date – date/time object. DateDiff returns the
number of intervals in units of datepart by which dates differ.
10. Dynamic expression evaluation functions allow expressions to be created dynamically using
string operations that are evaluated as needed. Using Dynamic Evaluation Functions, actual
expressions and variable names can be determined at run time when ColdFusion looks up
and replaces the variables with their values, calling any other functions, and performing any
required operations.
11. Evaluate() evaluates arguments, left to right; returns the result of evaluating the last
argument. This function takes as parameters, string expressions that are to be evaluated.
<cfoutput> #Evaluate(“1+2”)# </cfoutput>
Gives the output 3
12. GetDirectoryFromPath - this function extracts the directory (with a backslash) from a fully
specified path. This function takes one parameter—the path that is the drive, directory,
filename, and extension
GetFileFromPath - this function extracts the filename from a fully specified path. It takes
one parameter – the fully qualified path, i.e. the drive, directory, filename and extension.
13. GetBaseTemplatePath() would give you the path of your code template.
14. The parameters are the key, which generates the seed and the string to encrypt. The security
of the string depends on the secrecy of the key.
15. The purpose of the isDefined() function is to check the existence of a variable before it is
used. The two situations where this function is really valuable are:
a) To check for the existence of a variable before initializing the value of a textbox with that
variable’s value.
b) Enables you to use a single template for form and action checking for the existence of the
submit button to decide whether to execute the action part or the form part.
True/False
Answers:
1.
True - this function extracts the filename from a fully specified path, i.e. the drive,
directory, filename and extension.
CF_IM07-5
ColdFusion
Chapter 7: Built-In Functions
2.
True - decrypt takes two parameters—the encrypted string and key or the seed used to
generate the 32-bit key used to encrypt the string. This function decrypts the string using the
same key used to encrypt the string.
3.
False - DatePart returns part of a date as an integer. For example, year can be returned as
2002 or month as 1 for January.
4.
False - Rtrim trims trailing spaces in strings.
5.
True - we can use the mid() function or the left() function.
Example: leftmost 3 characters of string str can be extracted in two ways: left(str, 3) or
mid(str, 0, 3)
6.
False - Replace is a case sensitive search and replace function and ReplaceNoCase is a case
insensitive search and replace function.
7.
False – this will output 6 because evaluate() evaluates the value of the string within quotes.
8.
False - system functions act on server files and directories.
9.
True - ColdFusion indices start from 1 not 0.
10. True - Dateformat is used for formatting dates for output.
Programming Exercises
Answers:
1.
See ch07_ex01-sol.cfm
2.
See ch07_ex02-sol.cfm
3. See ch07_ex03-sol.cfm
4.
a)
IsLeapYear() takes a year as the parameter, not the entire date.
<cfif IsLeapYear(datepart(“yyyy”, now()))>
This is a leap year
</cfif>
b)
The fourth parameter should be in quotes.
<cfoutput>
#ReplaceNoCase(stringToSearch, "the", "a", "ONE")#<br />
</cfoutput>
Project Building Exercises
Answers:
1.
Done as part of the Shopping Cart Project (Phase 1). See review.cfm
2.
Done as part of the Shopping Cart Project (Phase 1). See SaveOrder.cfm
CF_IM07-6
Download