VBScript - Quick Guide

VBScript - Overview

VBScript stands for Visual Basic Scripting that forms a subset of Visual Basic for Applications (VBA). VBA is a product of Microsoft which is included NOT only in other Microsoft products such as MS Project and MS Office but also in Third Party tools such as AUTO CAD.

Features of VBScript

VBScript is a lightweight scripting language, which has a lightning fast interpreter.

VBScript, for the most part, is case insensitive. It has a very simple syntax, easy to learn and to implement.

Unlike C++ or Java, VBScript is an object-based scripting language and NOT an Object-Oriented Programming language.

It uses Component Object Model (COM) in order to access the elements of the environment in which it is executing.

Successful execution of VBScript can happen only if it is executed in Host Environment such as Internet Explorer (IE), Internet Information Services (IIS) and Windows Scripting Host (WSH)

VBscript – Version History and Uses

VBScript was introduced by Microsoft way back in 1996 and its first version was 1.0. The current stable version of VBScript is 5.8, which is available as part of IE8 or Windows 7. The VBScript usage areas are aplenty and not restricted to the below list.

VBScript is used as a scripting language in one of the popular Automation testing tools – Quick Test Professional abbreviated as QTP

Windows Scripting Host, which is used mostly by Windows System administrators for automating the Windows Desktop.

Disadvantages

VBscript is used only by IE Browsers. Other browsers such as Chrome, Firefox DONOT Support VBScript. Hence, JavaScript is preferred over VBScript.

VBScript has a Limited command line support.

Since there is no development environment available by default, debugging is difficult.

Where VBScript is Today ?

The current version of VBScript is 5.8, and with the recent development of .NET framework, Microsoft has decided to provide future support of VBScript within ASP.NET for web development. Hence, there will NOT be any more new versions of VBScript engine but the entire defect fixes and security issues are being addressed by the Microsoft sustaining Engineering Team. However, VBScript engine would be shipped as part of all Microsoft Windows and IIS by default.

VBScript - Syntax

Your First VBScript

In the above example, we called a function document.write, which writes a string into the HTML document. This function can be used to write text, HTML or both. So, above code will display following result −

Hello World!

Whitespace and Line Breaks

VBScript ignores spaces, tabs, and newlines that appear within VBScript programs. One can use spaces, tabs, and newlines freely within the program, so you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.

Formatting

VBScript is based on Microsoft's Visual Basic. Unlike JavaScript, no statement terminators such as semicolon is used to terminate a particular statement.

Single Line Syntax

Colons are used when two or more lines of VBScript ought to be written in a single line. Hence, in VBScript, Colons act as a line separator.

Multiple Line Syntax

When a statement in VBScript is lengthy and if user wishes to break it into multiple lines, then the user has to use underscore "_". This improves the readability of the code. The following example illustrates how to work with multiple lines.

Reserved Words

The following list shows the reserved words in VBScript. These reserved words SHOULD NOT be used as a constant or variable or any other identifier names.

Loop

LSet

Me

Mod

New

Next

Not

Nothing

Null

On

Option

Optional

Or

ParamArray

Preserve

Private

Public

RaiseEvent

ReDim

Rem

Resume

RSet

Select

Set

Shared

Single

Static

Stop

Sub

Then

To

True

Type

And

As

Boolean

ByRef

Byte

ByVal

Call

Case

Class

Const

Currency

Debug

Dim

Do

Double

Each

Else

ElseIf

Empty

End

EndIf

Enum

Eqv

Event

Exit

False

For

Function

Get

GoTo

If

Imp

Implements

In

Integer

Is

Let

Like

Long

TypeOf

Until

Variant

Wend

While

With

Xor

Eval

Execute

Msgbox

Erase

ExecuteGlobal

Option Explicit

Randomize

SendKeys

Case Sensitivity

VBScript is a case-insensitive language. This means that language keywords, variables, function names and any other identifiers need NOT be typed with a consistent capitalization of letters. So identifiers int_counter, INT_Counter and INT_COUNTER have the same meaning within VBScript.

Comments in VBScript

Comments are used to document the program logic and the user information with which other programmers can seamlessly work on the same code in future. It can include information such as developed by, modified by and it can also include incorporated logic. Comments are ignored by the interpreter while execution. Comments in VBScript are denoted by two methods.

1. Any statement that starts with a Single Quote (‘) is treated as comment.

Enabling VBScript in Browsers

Not all the modern browsers support VBScript. VBScript is supported just by Microsoft's Internet Explorer while other browsers (Firefox and Chrome) support just JavaScript. Hence, developers normally prefer JavaScript over VBScript.

Though Internet Explorer (IE) supports VBScript, you may need to enable or disable this feature manually. This tutorial will make you aware of the procedure of enabling and disabling VBScript support in Internet Explorer.

VBScript in Internet Explorer

Here are simple steps to turn on or turn off VBScript in your Internet Explorer −

Follow Tools → Internet Options from the menu

Select Security tab from the dialog box

Click the Custom Level button

Scroll down till you find Scripting option

Select Enable radio button under Active scripting

Finally click OK and come out

To disable VBScript support in your Internet Explorer, you need to select Disable radio button under Active scripting.

VBScript - Placements

VBScript Placement in HTML File

There is a flexibility given to include VBScript code anywhere in an HTML document. But the most preferred way to include VBScript in your HTML file is as follows −

Script in <head>...</head> section.

Script in <body>...</body> section.

Script in <body>...</body> and <head>...</head> sections.

Script in an external file and then include in <head>...</head> section.

In the following section, we will see how we can put VBScript in different ways −

VBScript in <head>...</head> section

If you want to have a script run on some event, such as when a user clicks somewhere, then you will place that script in the head as follows −

It will produce the following result − A button with the name SayHello. Upon clicking on the Button, the message box is displayed to the user with the message "Hello World".

VBScript in <body>...</body> section

If you need a script to run as the page loads so that the script generates content in the page, the script goes in the <body> portion of the document. In this case, you would not have any function defined using VBScript −

It will produce the following result − Hello World message with a 'Say Hello' button. Upon Clicking on the button a message box with a message "Hello World" is displayed to the user.

Hello World

VBScript in External File

As you begin to work more extensively with VBScript, you will likely find that there are cases, where you are reusing identical VBScript code on multiple pages of a site. You are not restricted to be maintaining identical code in multiple HTML files.

The script tag provides a mechanism to allow you to store VBScript in an external file and then include it into your HTML files. Here is an example to show how you can include an external VBScript file in your HTML code using script tag and its src attribute −

To use VBScript from an external file source, you need to write your all VBScript source code in a simple text file with extension ".vbs" and then include that file as shown above. For example, you can keep the following content in filename.vbs file and then you can use sayHello function in your HTML file after including filename.vbs file.

Function sayHello()
Msgbox "Hello World"
End Function

VBScript Placement in QTP

VBScript is placed in QTP (Quick Test Professional) tool but it is NOT enclosed within HTML Tags. The Script File is saved with the extension .vbs and it is executed by Quick Test Professional execution engine.

VBScript - Variables

VBScript Variables

A variable is a named memory location used to hold a value that can be changed during the script execution. VBScript has only ONE fundamental data type, Variant.

Rules for Declaring Variables −

Variable Name must begin with an alphabet.

Variable names cannot exceed 255 characters.

Variables Should NOT contain a period (.)

Variable Names should be unique in the declared context.

Declaring Variables

Variables are declared using “dim” keyword. Since there is only ONE fundamental data type, all the declared variables are variant by default. Hence, a user NEED NOT mention the type of data during declaration.

Example 1 − In this Example, IntValue can be used as a String, Integer or even arrays.

Dim Var

Example 2 − Two or more declarations are separated by comma(,)

Dim Variable1,Variable2

Assigning Values to the Variables

Values are assigned similar to an algebraic expression. The variable name on the left hand side followed by an equal to (=) symbol and then its value on the right hand side.

Rules

The numeric values should be declared without double quotes.

The String values should be enclosed within double quotes(")

Date and Time variables should be enclosed within hash symbol(#)

Examples

' Below Example, The value 25 is assigned to the variable.
Value1 = 25
' A String Value ‘VBScript’ is assigned to the variable StrValue.
StrValue = “VBScript”
' The date 01/01/2020 is assigned to the variable DToday.
Date1 = #01/01/2020#
' A Specific Time Stamp is assigned to a variable in the below example.
Time1 = #12:30:44 PM#

Scope of the Variables

Variables can be declared using the following statements that determines the scope of the variable. The scope of the variable plays a crucial role when used within a procedure or classes.

Dim

Public

Private

Dim

Variables declared using “Dim” keyword at a Procedure level are available only within the same procedure. Variables declared using “Dim” Keyword at script level are available to all the procedures within the same script.

Example − In the below example, the value of Var1 and Var2 are declared at script level while Var3 is declared at procedure level.

Note − The scope of this chapter is to understand Variables. Functions would be dealt in detail in the upcoming chapters.

Private

Variables that are declared as "Private" have scope only within that script in which they are declared. When declaring a variable of type "Private", Dim keyword is replaced by "Private".

Example − In the following example, Var1 and Var2 are available at Script Level. Var3 is declared as Private and it is available only for this particular script. Use of "Private" Variables is more pronounced within the Class.

VBScript - Constants

Constant is a named memory location used to hold a value that CANNOT be changed during the script execution. If a user tries to change a Constant Value, the Script execution ends up with an error. Constants are declared the same way the variables are declared.

Declaring Constants

Syntax

[Public | Private] Const Constant_Name = Value

The Constant can be of type Public or Private. The Use of Public or Private is Optional. The Public constants are available for all the scripts and procedures while the Private Constants are available within the procedure or Class. One can assign any value such as number, String or Date to the declared Constant.

Example 1

In this example, the value of pi is 3.4 and it displays the area of the circle in a message box.

An if else statement consists of a Boolean expression followed by one or more statements. If the condition is True, the statements under the If statements are executed. If the condition is false, then the Else part of the script is Executed

A switch statement allows a variable to be tested for equality against a list of values.

VBScript - Loops

There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

Programming languages provide various control structures that allow more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in VBScript.

VBScript provides the following types of loops to handle looping requirements. Click the following links to check their detail.

Terminates the Do While statement and transfers execution to the statement immediately following the loop

VBScript - Events

What is an Event ?

VBScript's interaction with HTML is handled through events that occur when the user or browser manipulates a page. When the page loads, that is an event. When the user clicks a button, that click too is an event. Other examples of events include pressing any key, closing window, resizing window, etc. Developers can use these events to execute VBScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable to occur.

Events are a part of the Document Object Model (DOM) and every HTML element has a certain set of events, which can trigger VBScript Code. Please go through this small tutorial for a better understanding HTML Event Reference. Here, we will see few examples to understand a relation between Event and VBScript.

onclick Event Type

This is the most frequently used event type, which occurs when a user clicks mouse's left button. You can put your validation, warning, etc., against this event type.

It will produce the following result, and when you click the Hello button, the onclick event will occur which will trigger sayHello() function.

onsubmit event type

Another most important event type is onsubmit. This event occurs when you try to submit a form. So you can put your form validation against this event type. The Form is submitted by clicking on Submit button, the message box appears.

The Form is submitted by clicking on Submit button, the message box appears.

onmouseover and onmouseout

These two event types will help you to create nice effects with images or even with text as well. The onmouseover event occurs when you bring your mouse over any element and the onmouseout occurs when you take your mouse out from that element.

It will produce a result when you hover the mouse over the text box and also when you move the focus away from the text box and the button.

HTML 4 Standard Events

The standard HTML 4 events are listed here for your reference. Here, script indicates a VBScript function to be executed against that event.

Event

Value

Description

onchange

script

Script runs when the element changes

onsubmit

script

Script runs when the form is submitted

onreset

script

Script runs when the form is reset

onblur

script

Script runs when the element loses focus

onfocus

script

Script runs when the element gets focus

onkeydown

script

Script runs when key is pressed

onkeypress

script

Script runs when key is pressed and released

onkeyup

script

Script runs when key is released

onclick

script

Script runs when a mouse click

ondblclick

script

Script runs when a mouse double-click

onmousedown

script

Script runs when mouse button is pressed

onmousemove

script

Script runs when mouse pointer moves

onmouseout

script

Script runs when mouse pointer moves out of an element

onmouseover

script

Script runs when mouse pointer moves over an element

onmouseup

script

Script runs when mouse button is released

VBScript and Cookies

What are Cookies?

Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website, it is required to maintain session information among different pages. For example, one user registration ends after completing many pages. But how to maintain user's session information across all the web pages. In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions and other information required for better visitor experience or site statistics.

How It Works?

Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier. Cookies are a plain text data record of 5 variable-length fields −

Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.

Domain − The domain name of your site.

Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.

Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.

Name=Value − Cookies are set and retrieved in the form of key and value pairs.

Cookies were originally designed for CGI programming and cookies' data is automatically transmitted between the web browser and web server, so CGI scripts on the server can read and write cookie values that are stored on the client.

VBScript can also manipulate cookies using the cookie property of the Document object. VBScript can read, create, modify and delete the cookie or cookies that apply to the current web page.

Storing Cookies

The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this −

Syntax

document.cookie = "key1 = value1;key2 = value2;expires = date"

Here expires attribute is optional. If you provide this attribute with a valid date or time, then cookie will expire at the given date or time and after that cookies' value will not be accessible.

It will produce the following result. Now enter something in the textbox and press the button "Set Cookie" to set the cookies.

Enter name:

Now, your system has a cookie called name. You can set multiple cookies using multiple key = value pairs separated by comma. You will learn how to read this cookie in next section.

Reading Cookies

Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So, you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name = value pairs separated by semicolons where name is the name of a cookie and value is its string value. You can use strings' split() function to break the string into key and values as follows −

Example

Following is the example to get the cookies set in the previous section −

Note − Here, UBound is a method of Array class, which returns the length of an array. We will discuss Arrays in a separate chapter; until that time, please try to digest it.

It will produce the following result. Now, press the button "Get Cookie" to see the cookies, which you have set in previous section.

Note − There may be some other cookies already set on your machine. So, above code will show you all the cookies set at your machine.

Setting the Cookies Expiration Date

You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiration date within the cookie. This can be done by setting the expires attribute to a date and time.

Example

The following example illustrates how to set cookie expiration date after 1 Month −

VBScript - Numbers

Number functions help the developers to handle numbers in an efficient way and also helps them to convert their subtypes. It also helps them to make use of the inbuilt mathematical functions associated with VBScript.

Number Conversion Functions

Number functions help us to convert a given number from one data subtype to another data subtype.

Syntax

Examples

String Functions

There are predefined VBScript String functions, which help the developers to work with the strings very effectively. Below are String methods that are supported in VBScript. Please click on each one of the methods to know in detail.

Returns a String after reversing the sequece of the characters of the given string.

VBScript - Arrays

What is an Array?

We know very well that a variable is a container to store a value. Sometimes, developers are in a position to hold more than one value in a single variable at a time. When a series of values is stored in a single variable, then it is known as an array variable.

Array Declaration

Arrays are declared the same way a variable has been declared except that the declaration of an array variable uses parenthesis. In the following example, the size of the array is mentioned in the brackets.

When we save the above script as HTML and execute it in Internet Explorer, it produces the following result.

XYZ
41.25
22
3
4
5
6
7

Array Methods

There are various inbuilt functions within VBScript which help the developers to handle arrays effectively. All the methods that are used in conjunction with arrays are listed below. Please click on the method name to know in detail.

VBScript - Procedures

What is a Function?

A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing same code over and over again. This will enable programmers to divide a big program into a number of small and manageable functions. Apart from inbuilt Functions, VBScript allows us to write user-defined functions as well. This section will explain you how to write your own functions in VBScript.

Function Definition

Before we use a function, we need to define that particular function. The most common way to define a function in VBScript is by using the Function keyword, followed by a unique function name and it may or may not carry a list of parameters and a statement with an End Function keyword, which indicates the end of the function.

Function Parameters

Till now, we have seen function without a parameter, but there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters. The Functions are called using the Call Keyword.

Returning a Value from a Function

A VBScript function can have an optional return statement. This is required if you want to return a value from a function. For example, you can pass two numbers in a function and then you can expect from the function to return their multiplication in your calling program.

NOTE − A function can return multiple values separated by comma as an array assigned to the function name itself.

Example

This function takes two parameters and concatenates them and returns result in the calling program. In VBScript, the values are returned from a function using function name. In case if you want to return two or more values, then the function name is returned with an array of values. In the calling program, the result is stored in the result variable.

VBScript - Dialog Boxes

What is a Dialog Box ?

VBScript allows the developers to interact with the user effectively. It can be a message box to display a message to a user or an input box with which user can enter the values.

VBScript MsgBox Function

The MsgBox function displays a message box and waits for the user to click a button and then an action is performed based on the button clicked by the user.

Syntax

MsgBox(prompt[,buttons][,title][,helpfile,context])

Parameter Description

Prompt − A Required Parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then we can separate the lines using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line.

buttons − An Optional Parameter. A Numeric expression that specifies the type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box. If left blank, the default value for buttons is 0.

Title − An Optional Parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar.

helpfile − An Optional Parameter. A String expression that identifies the Help file to use to provide context-sensitive help for the dialog box.

context − An Optional Parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided.

The Buttons parameter can take any of the following values −

0 vbOKOnly Displays OK button only.

1 vbOKCancel Displays OK and Cancel buttons.

2 vbAbortRetryIgnore Displays Abort, Retry, and Ignore buttons.

3 vbYesNoCancel Displays Yes, No, and Cancel buttons.

4 vbYesNo Displays Yes and No buttons.

5 vbRetryCancel Displays Retry and Cancel buttons.

16 vbCritical Displays Critical Message icon.

32 vbQuestion Displays Warning Query icon.

48 vbExclamation Displays Warning Message icon.

64 vbInformation Displays Information Message icon.

0 vbDefaultButton1 First button is default.

256 vbDefaultButton2 Second button is default.

512 vbDefaultButton3 Third button is default.

768 vbDefaultButton4 Fourth button is default.

0 vbApplicationModal Application modal. The current application will not work until the user responds to the message box.

4096 vbSystemModal System modal. All applications will not work until the user responds to the message box.

The above values are logically divided into four groups: The first group(0 to 5) indicates the buttons to be displayed in the message box. The second group (16, 32, 48, 64) describes the sytle of the icon to be displayed, the third group (0, 256, 512, 768) indicates which button must be the default, and the fourth group (0, 4096) determines the modality of the message box.

When the above script is executed, the message box is displayed, and if you press No Button, then the value of a is 7.

The Value of a is 7

VBScript InputBox Function

The InputBox function helps the user to get the values from the user. After entering the values, if the user clicks the OK button or presses ENTER on the keyboard, the InputBox function will return the text in the text box. If the user clicks on the Cancel button, the function will return an empty string ("").

Syntax

InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])

Parameter Description

Prompt − A Required Parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then we can separate the lines using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line.

Title − An Optional Parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar.

Default − An Optional Parameter. A default text in the text box that the user would like to be displayed.

XPos − An Optional Parameter. The Position of X axis which represents the prompt distance from left side of the screen horizontally. If left blank, the input box is horizontally centered.

YPos − An Optional Parameter. The Position of Y axis which represents the prompt distance from left side of the screen Vertically. If left blank, the input box is Vertically centered.

helpfile − An Optional Parameter. A String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box.

context − An Optional Parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided.

A Global Object with which we can send output to the Microsoft script debugger.

VBScript - Regular Expressions

Regular Expressions is a sequence of characters that forms a pattern, which is mainly used for search and replace. The purpose of creating a pattern is to match specific strings, so that the developer can extract characters based on conditions and replace certain characters.

RegExp Object

RegExp object helps the developers to match the pattern of strings and the properties and methods help us to work with Regular Expressions easily. It is similar to RegExp in JavaScript

Properties

Pattern − The Pattern method represents a string that is used to define the regular expression and it should be set before using the regular expression object.

IgnoreCase − A Boolean property that represents if the regular expression should be tested against all possible matches in a string if true or false. If not specified explicitly, IgnoreCase value is set to False.

Global − A Boolean property that represents if the regular expression should be tested against all possible matches in a string. If not specified explicitly, Global value is set to False.

Methods

Test(search-string) − The Test method takes a string as its argument and returns True if the regular expression can successfully be matched against the string, otherwise False is returned.

Replace(search-string, replace-string) − The Replace method takes 2 parameters. If the search is successful then it replaces that match with the replace-string, and the new string is returned. If there are no matches then the original search-string is returned.

Execute(search-string) − The Execute method works like Replace, except that it returns a Matches collection object, containing a Match object for each successful match. It doesn't modify the original string.

Matches Collection Object

The Matches collection object is returned as a result of the Execute method. This collection object can contain zero or more Match objects and the properties of this object are read-only.

Count − The Count method represents the number of match objects in the collection.

Item − The Item method enables the match objects to be accessed from matches collections object.

Match Object

The Match object is contained within the matches collection object. These objects represent the successful match after the search for a string.

FirstIndex − It represents the position within the original string where the match occurred. This index are zero-based which means that the first position in a string is 0.

Length − A value that represents the total length of the matched string.

Value − A value that represents the matched value or text. It is also the default value when accessing the Match object.

All about Pattern Parameter

The pattern building is similar to PERL. Pattern building is the most important thing while working with Regular Expressions. In this section, we will deal with how to create a pattern based on various factors.

Position Matching

The significance of position matching is to ensure that we place the regular expressions at the correct places.

Symbol

Description

^

Matches only the beginning of a string.

$

Match only the end of a string.

\b

Matches any word boundary

\B

Matches any non-word boundary

Literals Matching

Any form of characters such as alphabet, number or special character or even decimal, hexadecimal can be treated as a Literal. Since few of the characters have already got a special meaning within the context of Regular Expression, we need to escape them using escape sequences.

Symbol

Description

Alphanumeric

Matches alphabetical and numerical characters only.

\n

Matches a new line.

\[

Matches [ literal only

\]

Matches ] literal only

\(

Matches ( literal only

\)

Matches ) literal only

\t

Matches horizontal tab

\v

Matches vertical tab

\|

Matches | literal only

\{

Matches { literal only

\}

Matches } literal only

\\

Matches \ literal only

\?

Matches ? literal only

\*

Matches * literal only

\+

Matches + literal only

\.

Matches . literal only

\b

Matches any word boundary

\B

Matches any non-word boundary

\f

Matches a form feed

\r

Matches carriage return

\xxx

Matches the ASCII character of an octal number xxx.

\xdd

Matches the ASCII character of an hexadecimal number dd.

\uxxxx

Matches the ASCII character of an UNICODE literal xxxx.

Character Classes Matching

The character classes are the Pattern formed by customized grouping and enclosed within [ ] braces. If we are expecting a character class that should not be in the list, then we should ignore that particular character class using the negative symbol, which is a cap ^.

Symbol

Description

[xyz]

Match any of the character class enclosed within the character set.

[^xyz]

Matches any of the character class that are NOT enclosed within the character set.

.

Matches any character class except \n

\w

Match any word character class. Equivalent to [a-zA-Z_0-9]

\W

Match any non-word character class. Equivalent to [^a-zA-Z_0-9]

\d

Match any digit class. Equivalent to [0-9].

\D

Match any non-digit character class. Equivalent to [^0-9].

\s

Match any space character class. Equivalent to [ \t\r\n\v\f]

\S

Match any space character class. Equivalent to [^\t\r\n\v\f]

Repetition Matching

Repetition matching allows multiple searches within the regular expression. It also specifies the number of times an element is repeated in a Regular Expression.

Symbol

Description

*

Matches zero or more occurrences of the given regular Expression. Equivalent to {0,}.

+

Matches one or more occurrences of the given regular Expression. Equivalent to {1,}.

?

Matches zero or one occurrences of the given regular Expression. Equivalent to {0,1}.

{x}

Matches exactly x number of occurrences of the given regular expression.

{x,}

Match atleast x or more occurrences of the given regular expression.

{x,y}

Matches x to y number of occurences of the given regular expression.

Alternation & Grouping

Alternation and grouping helps developers to create more complex Regular Expressions in particularly handling intricate clauses within a Regular Expression which gives a great flexibility and control.

Symbol

Description

0

Grouping a clause to create a clause. "(xy)?(z)" matches "xyz" or "z".

|

Alternation combines one regular expression clause and then matches any of the individual clauses. "(ij)|(23)|(pq)" matches "ij" or "23" or "pq".

Building Regular Expressions

Given below are a few examples that clearly explain how to build a Regular Expression.

Regular Expression

Description

"^\s*.." and "..\s*$"

Represents that there can be any number of leading and trailing space characters in a single line.

"((\$\s?)|(#\s?))?"

Represents an optional $ or # sign followed by an optional space.

"((\d+(\.(\d\d)?)?))"

Represents that at least one digit is present followed by an optional decimals and two digits after decimals.

Example

The below example checks whether or not the user entered an email id whose format should match such that there is an email id followed by '@' and then followed by domain name.

Runtime errors

Runtime errors, also called exceptions, occur during execution, after interpretation. For example, the following line causes a runtime error because here syntax is correct but at runtime it is trying to call fnmultiply, which is a non-existing function −

Logical errors

Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result you expected. You cannot catch those errors, because it depends on your business requirement what type of logic you want to put in your program. For example, dividing a number by zero or a script that is written which enters into infinite loop.

Err Object

AAssume if we have a runtime error, then the execution stops by displaying the error message. As a developer, if we want to capture the error, then Error Object is used.

Example

In the below example, Err.Number gives the error number and Err.Description gives error description.

VBScript Miscellaneous Statements

VBScript has a few other important statements to help developers develop an efficient script. The following table lists a set of such important statements. In this chapter, we will discuss each of these statements in detail with examples.

Category

Function Name/Statement Name

Options

Option Explicit

Script Engine ID

ScriptEngine

variants

IsArray, IsEmpty, IsNull, IsNumeric, IsObject, TypeName

Expression

Eval,Execute

Control Statement

With...End With

Math Function

Randomize

Option Explicit

Option Explicit forces the developer to declare the variables using Dim statement before they are used in some part of the code.

Syntax

Option Explicit

Example

If we use Option Explicit and if we don't declare the variables then the interpreter will throw and error.

ScriptEngine

ScriptEngine represents the details of the scripting language in use. It is also used in combination with ScriptEngineMajorVersion, ScriptEngineMinor Version, ScriptEngineBuildVersion which gives the major version of the vbscript engine, minor version the vbscript engine, and the build version of vbscript respectively.

Save the file with .html extension upon executing the script in IE , the following result is displayed on the screen.

Version VBScript - 5.8.16996

IsEmpty

The Function IsEmpty is used to check whether or not the expression is empty. It returns a Boolean value. IsEmpty returns True if the variable is uninitialized or explicitly set to Empty. Otherwise the expression returns False.

Save the file with .html extension upon executing the script in IE, the following result is displayed on the screen.

Line 1 : False
Line 2 : True
Line 3 : False

IsObject

The IsObject Function is used to check whether or not the expression has a valid Object. It returns a Boolean value. IsObject returns True if the expression contains an object subtype otherwise the expression returns False.

Save the file with .html extension upon executing the script in IE, the following result is displayed on the screen.

Line 1 : True
Line 2 : False

IsNumeric

The IsNumeric Function is used to check whether or not the expression has a number subtype. It returns a boolean value. IsObject returns True if the expression contains an number subtype otherwise the expression returns False.

Eval

The Eval Function executes an expression and returns the result either as a string or a number.

Syntax

Eval(expression)

The argument Expression can be a string expression or a number. If you pass to the Eval function a string that doesn't contain a numeric expression or a function name but only a simple text string, a run-time error occurs. For example, Eval("VBScript") results in an error.

Save the file with .html extension upon executing the script in IE, the following result is displayed on the screen.

20
false
15

Execute

The Execute statement accepts argument that is a string expression containing one or more statements for execution.

Syntax

Execute(expression)

In VBScript, a = b can be interpreted two ways. It can be treated as an assignment statement where the value of x is assigned to y. It can also be interpreted as an expression that tests if a and b have the same value. If they do, result is True; if they are not, result is False. The Execute statement always uses the first interpretation while the Eval statement always uses the second.