Use these bookmarks to jump around the tutorial:
You’ve gotten a handle on the conditionals. You can do a loop. Now it’s time to learn about some of the built in functions that make life a whole lot easier.
And now for my
disclaimer. Many of the functions that we talk about below will have additional
features that we will not cover in this short tutorial. If you would like more
information on the functions or any of the other topics we cover in this series,
be sure to check out Microsoft’s online documentation at
http://msdn.microsoft.com.
Do
the Math
Even though you probably
won’t be doing much serious math in most of your ASP applications, it’s still a
good idea to review some of the more common math functions. Being that as it
may, here are the more common VBScript mathematical functions:
Mathematics:
|
|
ABS( ) | This stands for ABSolute value. An absolute value, if you remember from math class, is simply taking any number and eliminating the sign so that any number returned here is essentially a positive number. . |
INT( ) | This function will probably get more use than any of the other mathematical functions we list here with maybe the exception of the randomizing functions below. What INT does is simply turn any decimal number into an integer (whole) number. It does this by whacking off everything after the decimal point. That means there is no rounding going on here, it simply throws away the fractional part of any number that you give it. For example, if you give INT( ) the number 7.694, it will return then number 7.
|
LOG( ) | This function returns the natural logarithm of the number that you give it.
|
Trigonometry:
|
|
SIN( ) | I’m sure you already guessed that this is sine. Now, I’m not going to go into detail on the uses of sine because you probably already know what sine is used for. If you don’t, you may want to see if you can dig up one of your old math books before you start plugging in this function.
|
COS( ) | This function returns the cosine of the angle that you give it.
|
TAN( ) | This function returns the tangent of the angle that you give it.
|
ATN( ) | This function returns the arctangent of the number that you give it.
|
Miscellaneous:
|
|
RANDOMIZE | This particular math function does not actually return a result. What Randomize does is set a seed for random number generation. In short, it gets the ball rolling so that you can generate random numbers.
|
RND( ) | This is the function that actually generates a random number. Unlike our other math functions above, you don’t actually give this function a number to crunch. To see how RANDOMIZE and RND( ) work hand-in-hand, check out our practical example below. |
Before we get into the
randomizing functions, let’s take a second to look at how the other mathematical
functions work. Using the mathematical functions above is quite simple. Here’s
an example of how to use TAN( ):
decTangent =
TAN(intAngle)
It’s as simple as giving
the function a number to crunch and letting it do the rest. The above example
applies to pretty much every function that we mentioned above with the exception
of the randomizing functions.
RANDOMIZE and
RND( ) are a bit different. In order to effectively demonstrate them in use
I’ve come up with this installments practical example, a randomly displayed
banner ad:
<% Option
Explicit %>
<% ‘ Banner Ad
Rotation %>
<% Dim decRandomNumber %>
<% RANDOMIZE %>
<% decRandomNumber = RND( ) %>
<% If decRandomNumber > .5 then %>
<a HREF="http://www.adsite.com">
<IMG width="468" height="60" src="BannerAd1.jpg">
</a>
<% Else %>
<a HREF="http://www.otheradsite.com">
<IMG width="468" height="60" src="BannerAd2.jpg">
</a>
<% End If %>
Now for an explanation
of how the code above works. First, we declare our variable that we are going to
use to store our random number, decRandomNumber.
Next we use the
RANDOMIZE function. This function sets the randomizing generator in motion
by seeding it. (Random number generators work by using a complex algorithm that
requires a seed number to kick-start the process. That seed number can be taken
any number of ways but usually involves a combination of the current date and
time.) You only need to use the RANDOMIZE function once on each ASP page
since it simply gets the process started. It can be used more than once but it
isn’t necessary.
The next function that
you will see is RND( ). RND( ) is the actual function that goes
out and retrieves your random number. We set our decRandomNumber variable
equal to the RND( ) function. This will set decRandomNumber equal
to a random number between 0 and 1.
Once we have our random
number set, it is a simple process of checking the number to see if it is
greater than .5 or not. That is where the If .. Then statement comes in. If our
number is greater than .5 then we display BannerAd1, otherwise we display
BannerAd2.
Right now each ad will
be displayed 50% of the time. To give more weight to one ad over another just
change how you make the comparison. For example, if you change the first part of
the If .. Then to say decRandomNumber > .75, BannerAd1 will only be
displayed 25% of the time. You can also add additional banner ads by adding in
an ElseIf or two. (Using the If .. Then, ElseIf and Else statements can be found
here.)
back to
top
Messing with Strings
Let’s move on to some
string functions. You will probably find yourself using string functions
infinitely more than the mathematical functions above. The reason is that most
of the data you interact with on the web is in the form of strings, i.e.
people’s names, addresses, web URL’s, e-mail addresses, etc.
Here are some of the
most commonly used string functions. I have tried to give an easy to understand
example of each function. We’ll discuss the practical applications of some of
the functions later. Here they are:
Changing Strings: | |
LCASE( ) | This function does exactly what you might think. It takes any string it gets and makes it all lower case. Example: Doing LCASE("Hello
|
UCASE( ) | This function is, of course, the polar opposite of LCASE( ). UCASE( ) changes any given string to all upper case.
Example: Taking the example above, doing UCASE("Hello World!")
|
LTRIM( ) | This function gets rid of extra spaces on the left side of any string by just chopping them off. Example: If you give LTRIM( )
|
RTRIM ( ) | This function does the opposite of LTRIM( ). It removes any extra spaces from the right side of any string. Example: The
|
TRIM( ) | TRIM( ) then is a combination of the two above. It will chop off any extra spaces before and after a given string. Example:
|
REPLACE( ) | Learn this one well. REPLACE( ) allows you to replace any given set of characters in a string with another set of characters.
Example: This function is a bit more complicated than the rest of the string strMySentence = "I like ice strNewSentence = REPLACE(strMySentence,"like","love") The result of the code above would be that strNewSentence would
|
All About the String: | |
LEN( ) | This is one of the few string functions that doesn’t actually return a string. Instead it returns the length of any given string as an integer. In other words, it counts the number of characters, including spaces, and gives you the total. Example: If you do LEN("Test
|
LEFT( ) | This function allows you to get a selected section of a string. It is done by giving the function the string you want a piece of and the length of that piece. It then counts from the left to a specified length and returns that piece of the string. Example: LEFT("I love ASP!",6)
|
RIGHT( ) | This function does the exact same process as LEFT( ) except from the right. Example: RIGHT("I love ASP!",4) would
|
MID( ) | As you might expect, MID( ) allows you to take a string out of the middle of another string. For this particular function you will need a starting point and the number of characters that you want. Example: MID("I love ASP!",3,4) will give you "love"
|
INSTR( ) | This function allows you to search for a string within a string. It works much like REPLACE( ) does in that you give it a string to search and a string to search for. The result it returns is the character number of the beginning of the match, if it finds one. If it doesn’t find a match it will return a 0. Example: INSTR("I love Here’s an extra little tip about INSTR("I love ASP!","asp") |
Now that you know some
of the string functions that you have available to you, I thought it might be a
good idea to give you some common uses for them.
UCASE( ) and
LCASE( ): These are very useful in eliminating case-sensitivity when you are
making comparisons. For example, let’s say someone enters an email address on a
form to look up their account information. You don’t want to tell them you can’t
find their account if they accidentally capitalized a character in their email.
So, to eliminate that possibility you might want to take the email address they
input on the form and transform it to all lower case with the LCASE( )
function before you make a comparison to the accounts in your database.
TRIM( ), LTRIM(
) and RTRIM( ): These functions are excellent for "cleaning up" a
user’s input. As a rule, I always use TRIM( ) on all input I get from
users. I like to eliminate any extra spaces up front so that they don’t cause me
any problems later. I very rarely use LTRIM( ) and RTRIM( ).
REPLACE( ): This
is one of the handiest functions around. You will find it very necessary for
eliminating problems when interacting with a database using SQL. You will also
find it very useful when trying to translate carriage returns into breaks (<BR>)
in HTML. I will show you specific examples of how REPLACE( ) is a
necessity when we get to some of the database stuff later.
LEN( ): This
function I find most useful when determining whether a user’s input is too long
or too short. If you are storing user input into a database you will often have
size limitations to contend with. This function can check those limits before
you generate an error writing to your database. It is also very useful for
parsing out search strings (we’ll get to that later).
LEFT( ),
RIGHT( ) and MID( ): These functions are great for chopping up user
input into single words or phrases. They are most handy in cooperation with
LEN( ) when separating out words in a user’s search string. I sometimes use
LEFT( ) to cut off user input that is too long.
INSTR( ): I find
this function most useful in searching for illegal words. For example, let’s say
your ASP page is posting user messages to a bulletin board. The bulletin board
is family oriented and you want to ensure that there is no bad language in any
of the postings. You can use INSTR( ) to deny messages where you find
offensive language.
back to
top
Nailing Down a Date & Time
As if you haven’t had
your fill of functions yet, here are some common functions used for manipulating
date and time:
DATE( ) | This function gets the current date.
|
TIME( ) | This function gets the current time.
|
NOW( ) | This function gets the current date and time.
|
MONTH( ) | This function pulls the month out of any date/time string variable and returns it as a integer.
|
DAY( ) | This function pulls the day out of any date/time string variable and returns it as a integer.
|
YEAR( ) | This function pulls the year out of any date/time string variable and returns it as a integer.
|
HOUR( ) | This function pulls the hours out of any date/time string variable and returns it as a integer.
|
MINUTE( ) | This function pulls the minutes out of any date/time string variable and returns it as a integer.
|
SECOND( ) | This function pulls the seconds out of any date/time string variable and returns it as a integer.
|
WEEKDAY( ) | This function is one of the more handy ones. It takes any date given it and tells you what day of the week it is. It does this by returning an integer number that indicates the day of the week. If a 1 is returned it is a Sunday, a 2 indicates a Monday, etc.
|
DATEDIFF( ) | This function allows you get the difference between two days. You can even select how the difference is calculated, i.e. days, hours, minutes, etc. Here’s how it works: DATEDIFF("d",DATE( The example above compares today’s date with the first day of 2002 and
|
DATEADD( ) | As you would imagine, this function adds two dates together and gives you the result. This function needs some very specific information in order to complete its task. It must know the date it needs to add to, the type of time that is being added (i.e. days, hours, minutes, etc.), and it needs to know how much time to add. Here is an example: DATEADD("h",12,NOW( The function above will add 12 hours ("h") to today’s date and time. The |
You probably won’t find
yourself manipulating dates and times as much as strings but you will use these
functions quite a bit. Here are some practical uses for the functions above:
DATE( ), TIME(
) and NOW( ): You will be surprised how often you need to get the
current date and time. I have used these functions for everything from
displaying the current day to time stamping data that I send to a database. You
will probably find DATE( ) and NOW( ) the most useful.
MONTH( ), DAY(
), HOUR( ), MINUTE( ), YEAR( ), SECOND( ): To be
completely honest with you, I will rarely use any of these functions. It is
useful, on occasion, to get the month, day or sometimes year out of a date but I
rarely have used the HOUR( ), MINUTE( ) and SECOND( )
functions.
WEEKDAY( ): This
is a very handy function for displaying a more full and formal date. I actually
use this one quite a bit whenever I need to display a complete date.
DATEDIFF( ) and
DATEADD( ): These functions are both very commonly used. I use
DATEDIFF( ) mostly for determining whether or not to display some data that
has an expiration attached to it. For example, displaying a special message
about a current sale until the sale expires. I use the DATEADD( )
function for determining expiration dates. It is quite handy quickly calculating
expiration dates for cookies and the like.
back to
top
What’s Next?
That’s it! This
concludes your crash course in VBScript. Now, there is much more to VBScript
than we have talked about up to this point but you have the basics. We will
cover additional features of VBScript as we come across them later in this
series.
Next it’s on to some
real ASP. You’ll finally begin putting together the pieces and start creating
some full-blown ASP applications.
In the next part of this series
we will:
-
Talk to the user with
Response.Write -
Give directions to the
user with Response.Redirect -
Store info about the
user with Response.Cookies