A reference for all of the keywords and statements used in Active Server Pages. Items are grouped by function and contain a short description and example of their usage.
This contains a quick reference of all of the language elements in Active Server Pages.
||This function creates an instance of an array. The arguments to this function are the elements you want to see the array with. It is possible to have no arguments at all.
aOption = Array("yes", "no", "unknown")
||Subroutine which clears all of the elements of the array. If the elements are numeric values, then they will all be set to zero. If the elements are strings then they will all be made empty.
||Selectively include or exclude elements from an array. The optional third argument is a boolean which indicates whether items are included.
Filter(aArray, "remove", False)
||Build a string by joining all of the elements in the array. A "glue string" is inserted between each element.
||Return the lower bound of an array meaning the smallest possible array index that may be used for the array. All arrays in ASP start with the index 0, so you shouldn't need to use this.
||Use this to re-dimension (or resize an array) after it has already been declared. If the Preserve keyword is used, existing elements will not be destroyed in the process.
ReDim Preserve aField(nCount + 10)
||Takes a string argument and creates an array by "splitting" the string into multiple elements. Strings are split based on a "delimitter" which is passed as the second argument.
aName = Split("joe,bill,john", ",")
||Return the upper bound of the array meaning the last possible array index. This is often used to get the size of an array (which in turn can be used in For...Next loops to iterate over the elements)
||Invoke a procedure (either a subroutine or a function). If used to invoke a function, the return value cannot be assigned (leave the Call keyword off if you want to do something with the return value)
Call SayHello("Bill Gates")
' alternative way to call a subroutine (notice no parentheses necessary)
SayHello "Bill Gates"
||Evaluate Active Server Pages code that is built dynamically. In other words, if you build a string (at runtime) containing ASP code, you can execute that code using Eval.
fArea = Eval("3.14159 * fRadius * fRadius")
||Execute an ASP script programatically. Allows you to execute an ASP page during runtime. Most normal methods of doing this (like using a server-side include) will process the script regardless of whether it is used or not. With Execute, you can conditionally process ASP scripts.
if (nThemeNo = 1) then
||Used to break execution out of a function, subroutine, or many of the looping constructs.
||This allows you to create a multi-branched conditional construct similar to a sequence of If Then ... Else If ... Else If ... Else ... End If.
Select Case nDayOfWeek
Case vbSunday : Response.Write "Day of Rest"
Case vbSaturday : Response.Write "Shopping Day"
Case vbMonday :
Case vbThursday : Response.Write "Dance Class"
Case Else : Response.Write "Work is Fun!"
||Calculate the absolute value of an expression (makes a negative result into a positive one)
||Trigonometry function to calculate the arc-tangent of a value
||Trigonometry function to calculate the cosine of a value
||Calculates the value of the expression e ^ y where e is a constant representing the base of the natural logarithm (otherwise known as napier's constant).
||Converts a number to an integer. Negative numbers are rounded up (instead of down which is how Int works). So a number like -5.99235 would result in a value of -5.
||Converts a numeric value into an integer value. It effectively does the same thing as the "Floor" function in that it truncates any fractional part of the number (not performing any rounding).
||Calculate the natural logarithm of a number. This is often expressed in mathematics as ln(y)
||Calculate the modulus (or remainder) between two numbers. This is a boolean operator just like + or /. The result of 10 Mod 3 is 1, because 3 goes into 10 at most 3 times with 1 left over (3 * 3 = 9 and 10 - 9 = 1)
||Seed the random number generator. Doesn't return a value but prepares the script to produce truly random numbers via the Rnd function.
||A function which returns a random number that is greater than or equal to zero and less than 1. You shoud always call Randomize before calling this function.
||A function which rounds a number to the closest integer. So if the fractional part of the number is < 0.5, the number will be rounded down, otherwise the number will be rounded up.
||Performs the sign function which returns only three possible values. -1 if the argument is a negative number, 1 if the number is positive, or 0 if the argument is exactly zero.
||Trigonetry function which returns the sine function. The argument is the angle of degrees in radians.
||Calculates the square root of a number. The argument must be a positive number greater than or equal to zero.
||Trigonometry function to calculate the tangent of a value. The argument is the angle of degrees in radians.
||Return the ASCII code for a character (the first character of a string since there is no character subtype in ASP)
||Returns the first byte of a sequence of binary data. Binary data is typically used when manipulating files.
||Returns the 32-bit wide (unicode) character code for the first character in a string
||Builds a single string (character) based on the ASCII code argument. This is how you can build a string containing non-printable characters. ASP contains many built-in constants which also serve this purpose (such as vbCr, vbLf and even vbCrLf).
sStr = "Hello World!" & Chr(13) & Chr(10)
||Formats a numeric value as currency according to the locale settings. The optional second argument indicates the number of places after the decimal point. In the United States, the default is two.
sGasPrice = FormatCurrency(3.00)
sNatlDebt = FormatCurrency(9065368997351, 0)
||Formats a numeric value according the locale settings for the server. It may insert digit separator (like the comma in 3,932) or pad the number with zeros. An optional second argument indicates the number of digits to show after the decimal point.
sPopulation = FormatNumber(9065368997351)
sPI = FormatNumber(3.1415926, 4)
||Format a number as a percentage value. Actually it converts a probability number from 0 to 1 into a percentage between 0% and 100%. An optional second argument indicates the number of digits shown after the decimal point.
nPct = FormatPercent(0.5442)
nPct2 = FormatPercent(0.5442542, 3)
||Find the first occurrence of one string within another. By default the search will do a case sensitive comparison. The first argument is the character index to start the search from. The second argument is the text to be searched (haystack) and the third argument is what you are looking for (the needle). The optional fourth argument allows you to specify the comparison type (like vbTextCompare or vbBinaryCompare)
nBeginPos = InStr(1, sText, "Begin", vbTextCompare)
||Find the first occurrence of one string within another starting from the end of the string and searching to the left. Unlike InStr, the optional position to start the search from is the third argument (instead of the first). The optional fourth argument allows you to specify the comparison type (like vbTextCompare or vbBinaryCompare)
nScriptPos = InStrRev(sURL, "/")
nProtocolPos = InStrRev(sURL, "http://", 100, vbTextCompare)
||Convert all alphabetic characters in a string to lowercase.
sUsername = LCase("WaCkYcAsEuSeR")
||Return a substring starting from the left side (first character) of the base string.
sFirst = Left(sFullName, 10)
||Given a string as the argument, returns the length of the string in characters.
||Trim any whitespace that exists on the left side of the string. So if you give the function an argument of " Hi! ", it would return the value "Hi! ".
||Get a subtring from a string. The first argument is the base string to extract the substring from. The second argument indicates the character index to start from. The last argument indicates the number of characters to extract. You may omit the last argument to retrieve all characters up to the end of the string.
sMiddle = Mid(sFullname, nMidStart, nMidEnd - nMidStart + 1)
sLast = Mid(sFullName, nLastStart)
||Replace all occurrences of the search string (argument 2) with the replacement string (argument 3) in the base string (argument 1) and return it.
sEscape = Replace(sSQL, "'", "''")
||Return a substring starting from the right side (last character) of the base string.
sLast = Right(sFullName, 13)
||Trim any whitespace that exists on the right side of the string. So if you give the function an argument of " Hi! ", it would return the value " Hi!".
||Build a string with a repeated number of spaces. When displayed as HTML, the browser will compress all whitespace unless the text is preformatted (in a <PRE>...</PRE> block) or the content is delivered in plain text.
Response.Write Space(30 - Len(sFirst)) & sFirst
||Compare two strings to see if they are equal or not. You may perform a binary (case sensitive) comparison (the default) or you can do a textual (case insensitive) comparison by passing the optional third parameter as vbTextCompare
if (StrComp(sFirst1, sFirst2, vbTextCompare)) Then Response.Write "EQUAL!"
||Creates a string by repeating a specified character a certain number of times. The first argument is the number of repetitions and the second argument is the string (character) to repeat.
sLine = String(80, "-")
sDblLine = String(80, "=")
||Take a string and reverse the order of the characters. In other words, given a string like "012345789", this function would return "9876543210".
sReverse = StrReverse("0123456789")
||Trim any whitespace that exists on either the right or left side of the string. So if you give the function an argument of " Hi! ", it would return the value "Hi!".
||Convert all alphabetic characters in a string to uppercase.
sUsername = UCase("WaCkYcAsEuSeR")
||Logical "AND" operations. Result is true only if both of the expressions evaluate to true, otherwise the result is False
If nScore > 80 And nScore < 90 Then sGrade = "B"
||Test a pair of boolean expressions and return true only when both of the expressions evaluate with the same result (both are true or both are false).
If nScore > 60 Eqv False Then
||This evaluates an expression (resulting in a boolean true or false) and conditionally executes ASP code based on the resulting
' example of a single-line If...Then
If nScore < 60 Then sGrade = "F"
' example of a multi-line If.. Then
If nScore < 60 Then
Response.Write "Sorry, You Failed"
Response.Write "Congratulations, You Passed"
||The "implication" operator is used to determine whether A implies B. The result is always true unless A is true and B is false.
If bCondA Imp bCondB Then Response.Write "It Implies"
||Use the is operator on variables containing objects to test if one object is the same as another (refers to the same instance). You can also use is to see if an object variable is set to nothing.
If oFile is nothing Then Response.Write "Nothing"
||This function determines if a variable contains an array. Returns true to indicate it does, or false meaning it does not.
If IsArray(aVar) Then nCount = UBound(aVar) + 1
||Test to see if the expression contains a valid date (either as a string which may be converted to a date using CDate or as date subtype)
If IsDate(dBirth) Then sBirthDay = FormatDateTime(dBirth)
||Check to see if a variable (or an expression) contains an empty value. An empty value is the default value for variables which have been declared but never assigned.
If IsEmpty(sVar) Then Response.Write "You forgot to define the variable ""sVar"""
||Check to see if a variable or an expression evaluates to null. This is particularly useful for database values retrievied using the ADODB component.
If IsNull(rs.Fields("lastname").value) Then bError = True
||Check to see if a variable or expression contains a numeric value or can be converted to a numeric value using CLng, CInt, CFlt, or CDbl.
If IsNumeric(sAmount) Then nAmount = CInt(sAmount)
||Test to see if a variable or expression refers to a valid object. An object can be created by calling the Server.CreatObject method.
If IsObject(oFile) Then oFile.Close
||Perform a negation operation on a boolean expression. Gives you the opposite of either true or false.
||Boolean "or" operation takes two arguments which must be boolean expressions. Returns true if either expression evaluates to true, otherwise returns false.
If bLovesSchool Or bLovesBoooks Then bIsSmart = true
bIsSmart = (bLovesSchool Or bLovesBoooks)
||The exclusive or operator only returns true when exactly one of the boolean expression arguments is true. Returns false when both arguments are false OR both arguments are true.
If (bLikesYankees Xor bLikesMets) Then bIsRealPerson = true
bGiveCake = (bJoeWantsCake Xor bJuneWantsCake)
||Return the date according the local system clock. Does not return any time information, just the date.
||Add a specific number of time units to the supplied date.
dTomorrow = DateAdd("d", 1, Now())
||Calculate the number of time units between two date arguments.
Response.Write "Hours = " & DateDiff("h", dTomorrow, Now())
||Extract a specific part of the datetime expression and return it. First argument may be "d" (day), "m" (month), "yyyy" (year), "q" (quarter), "w" (weekday), "ww" (week of year), "h" (hour), "n" (minute), or "s" (second).
nDay = DatePart("d", Now())
||Construct a date value from its individual components. The components are year (argument 1), month (argument 2) and day (argument 3).
dChristmas = DateSerial(2008, 12, 25)
||Attempt to convert a string containing a date value into a variable with subtype date. If the date is not formatted properly, the script will fail with an error.
dChristmas = DateValue("12/25/2008")
||Extract the day portion of a date expression. Shortcut for DatePart("d", dDate).
Response.Write "Christmas is on day " & Day(dChristmas)
||Format a datetime expression into human readable format. Format specifier (argument 2) may be one of: vbGeneralDate, vbLongDate, vbShortDate, vbLongTime, or vbShortTime.
sModified = FormatDateTime(dModified, vbGeneralDate)
||Extract the hour portion of a date expression. Shortcut for DatePart("h", dDate).
||Extract the minute portion of a date expression. Shortcut for DatePart("n", dDate).
||Extract the month portion of a date expression. Shortcut for DatePart("m", dDate).
||Returns the name of a month corresponding to a month number (1 to 12). The second argument is an optional boolean indicating whether the month name should be abbreviated (true) or not (false).
sMonth = MonthName(Month(dDate))
sMonth2 = MonthName(DateValue("12/25/2008"), true)
||Returns a datetime value which corresponds to the current server time.
Response.Write "Today is: " & Now()
||Extract the second portion of a date expression. Shortcut for DatePart("s", dDate).
||Returns a time value using the current server time. The date is not included in this value (for that you should use Now).
Response.Write "Time Right Now: " & Time()
||Returns a floating point value with the integer portion indicating whole seconds (since Jan 1, 1970) and the fractional part indicating milliseconds.
fStart = Timer()
' do some work here
fEnd = Timer()
fElapsed = fEnd - fStart
||Construct a variable with a subtype of time using the supplied arguments. Arguments are: hour, minute, and second.
dTime = TimeSerial(23, 59, 0)
||Attempt to convert a string (representing a valid time value) into a variable with subtype time. Throws an exception of the string is not properly formatted (and unable to convert).
dTime = TimeValue("23:59:00")
||Extract the day of the week (as an integer) for a datetime expression. The first day of the week is Sunday which is returned as 1. The last day of the week is Saturday which is returned as 7.
nWeekday = Weekday(DateValue("12/25/2008"))
||Extracts the day of the week (as a string) for a datetime expression.
sWeekday = WeekdayName(DateValue("12/25/2008"))
||Extract the year portion of a date or datetime expression. This is a shortcut for DatePart("yyyy", dDate).
Every variable in ASP is a variant (meaning the language is not strongly typed), so when we talk about type conversions, we're talking about the subtype of a variant value.
||Convert a variable into a boolean type (which can only hold true or false)
||Convert a variable into a byte type (integer from 0 to 255)
||Convert a variable into a currency type. This is just like a decimal number in that extra care is taken to ensure that nothing is lost in rounding).
fMoney = CCur(Request.Form("LoanAmount"))
||Convert a variable into a datetime value. The expression may be a date, a time, or a datetime expression.
dBirthday = CDate(Request.Form("BirthDay"))
||Convert a variable into a double type which is a double precision floating point number.
dVal = CDbl("23.3452e+04")
||Convert a variable into an integer type. An integer is a 2-byte signed value that is restricted to values between -32,768 to 32,767. Note that CInt() performs "Banker's Rounding"—it does not truncate the fractional portion. Use Int() to truncate variables to integers.
nIntVal = CInt(Request.Form("SATScore"))
||Convert a variable into a long integer type. A long integer is a 4-byte signed value that is restricted to values between -2,147,483,648 to 2,147,483,647. Note that CLng() performs "Banker's Rounding"—it does not truncate the fractional portion.
nLngVal = CLng(Request.Form("SerialNo"))
||Convert a variable into a floating point number (basically a float) which is also known as a single precision floating point number. Positive numbers are restricted to values between 1.401298E-45 to 3.402823E+38 and negative numbers are restricted to values between -3.402823E+38 to -1.401298E-45.
fTemp = CSng(Request.Form("Temperature")
||Convert a variable into a string value. This is often necessary when comparing two values where one is a different type.
if (CStr(nAge) = Request.Form("Age")) Then Response.Write "You're " & nAge
||Convert an integer number to hexadecimal equivalent. Hexadecimal is a "base 16" number with digits ranging from 0 to 9 and A to F. Hexagonal numbers are restricted to four-byte values so that converting a value of -1 results in the value FFFF.
||Convert an integer number to its octal equivalent. An octal number is a "base 8" number meaning the digits range from 0 to 7.
||Declare a new instance of a class by enclosing it between Class ... End Class. Contained inside the class may be member variable definitions, method definitions, and property definitions.
Private String sName
Private String nDays
sName = "Unknown"
' Abbreviation method
Public Function Abbreviation
Abbreviation = Left(sName, 3)
' retrieve the number of days
Property Get Days
Days = nDays
' assign the name for this month
Property Let Name
sName = Name
||Use this statement to declare a new instance of a class. The built-in class RegExp may be used to declare an instance of a regular expression object. You must use the Set statement when instantiating a new object.
Set oRE = New RegExp
oRE.Pattern = "\w+"
||This is an access modifier which may appear before a member variable, method, or properety. Any entity marked private may only be accessed within the class definition itself.
||This access modifer makes an entity public. So a public variable can be accessed using the "dot notation" from the instance of a class. Likewise for methods and properties. Note that Public is the default access modifier and you don't have to include an access modifier on all entities.
Public Function Abbreviation
||The Property Get statement allows you to declare a read-only property to your class. This is similar to a function in that it returns a value. If you try to do assignment using this property (oMonth.Days = 31), the parser will throw an exception.
||Use this property definition to define an assignor method. This allows you to assign a value to a class property. How the assignor method is implemented is up to you, but it usually modifies one of the member variables.
||If you need to define a property which assigns the value of an object, you should define a Property Set method. To define a property which retrieves an object value, you can simply use Property Get.
Property Set RegularExp
Set oRE = New RegExp
Set oMonth.RegularExp = oRE
||Assign an instance of an object to a variable.
||Use this function to retrieve the type of an object as a string. When used with a regular variable, it returns the subtype ("Date", "Double", "Integer", "String", "Boolean", etc.)
' another built-in object - Dictionary COM+ object
Set oHash = Server.CreateObject("Scripting.Dictionary")
' this will return the string "Dictionary"
Response.Write "Hash Type = " & TypeName(oHash)
||The With statement will save you some typing and allow you to access one instance of an object repeatedly by using a notation like .Write for the Response object. So instead of repeatedly typing Response.Write, you could do:
.Write " x "
.Write " = "