Unit 3 Up
Unit 3 Up
Scripts can appear directly as the content of a <script> tag. The type attribute of <script>
must be set to "text/javascript".
<!DOCTYPE.html>
<!-- hello.html
A trivial hello world example of HTML/JavaScript
-->
<html lang = "en">
<head>
<title> Hello world </title>
<meta charset = "utf-8" />
</head>
<body>
<script type = "text/javascript">
<!--
document.write("Hello, fellow Web programmers!");
// -->
</script>
</body>
</html>
1
The JavaScript script can be indirectly embedded in an HTML document with the src attribute of a
<script> tag, whose value is the name of a file that contains the script—for example,
<script type = "text/javascript" src = "tst_number.js" >
</script>
Example:
<!DOCTYPE html>
<!-- roots.html
A document for roots.js
-->
<html lang = "en">
<head>
<title> roots.html </title>
<meta charset = "utf-8" />
</head>
<body>
<script type = "text/javascript" src = "roots.js" >
</script>
</body>
</html>
// roots.js
// Compute the real roots of a given quadratic
// equation. If the roots are imaginary, this script
// displays NaN, because that is what results from
// taking the square root of a negative number
// Get the coefficients of the equation from the user
var a = prompt("What is the value of 'a'? \n", "");
var b = prompt("What is the value of 'b'? \n", "");
var c = prompt("What is the value of 'c'? \n", "");
// Compute the square root and denominator of the result
var root_part = Math.sqrt(b * b - 4.0 * a * c);
var denom = 2.0 * a;
// Compute and display the two roots
var root1 = (-b + root_part) / denom;
var root2 = (-b - root_part) / denom;
document.write("The first root is: ", root1, "<br />");
document.write("The second root is: ", root2, "<br />");
2
Java script reserved words:
Identifiers: They must begin with a letter, an underscore (_), or a dollar sign ($). Subsequent characters
may be letters, underscores, dollar signs, or digits.
Comments – two ways: First, whenever two adjacent slashes (//) appear on a line, the rest of the line
is considered a comment. Second, /* may be used to introduce a comment, and */ to terminate it, in
both single- and multiple-line comments.
Numeric: All numeric literals are primitive values of type Number. The Number type values are
represented internally in double-precision floating-point form. Because there is only a single numeric data
type, numeric values in JavaScript are often called numbers. Literal numbers in a script can have the forms
of either integer or floating-point values. Integer literals are strings of digits. Floating-point literals can
have decimal points, exponents, or both. Exponents are specified with an uppercase or lowercase ‘e’ and a
possibly signed integer literal. The following are valid numeric literals:
String literals: A string literal is a sequence of zero or more characters delimited by either single quotes (‘)
or double quotes (“).
Example: 'You are the most wonderful person I have ever seen'.
Null: The only value of type Null is the reserved word null, which indicates no value. A variable is null if it
has not been explicitly declared or assigned a value. If an attempt is made to use the value of a variable
whose value is null that will cause a runtime error.
Undefined: The only value of type Undefined is undefined. Unlike null, there is no reserved word
undefined. If a variable has been explicitly declared, but not assigned a value, it has the value undefined. If
the value of an undefined variable is displayed, the word undefined is displayed.
Boolean: The only values of type Boolean are true and false. These values are usually computed as the
result of evaluating a relational or Boolean expression.
Declaring Variables
4
A variable can be declared either by assigning it a value, in which case the interpreter implicitly declares it
to be a variable, or by listing it in a declaration statement that begins with the reserved word var. Initial
values can be included in a var declaration, as with some of the variables in the following declaration:
Numeric Operators
The binary operators + for addition, - for subtraction, * for multiplication, / for division, and % for
modulus.
The unary operators are plus (+), negate (-), decrement (--), and increment (++). The increment and
decrement operators can be either prefix or postfix.
Example:
For a=7: (++a) * 3 = 24 and (a++) * 3 = 21
Precedence and associativity of the numeric operators:
Example:
Parentheses can be used to force any desired precedence. For example, the addition will be done before
the multiplication in the following expression: (a + b) * c
The Math Object
5
The Math object provides a collection of properties of Number objects and methods that operate on Number
objects. The Math object has methods for the trigonometric functions, such as sin (for sine) and cos (for
cosine), as well as for other commonly used mathematical operations. Among these are floor, to truncate a
number; round, to round a number; and max, to return the largest of two given numbers. All of the Math
methods are referenced through the Math object, as in Math.sin(x).
Any arithmetic operation that results in an error (e.g., division by zero) or that produces a value that cannot be
represented as a double-precision floating point number, such as a number that is too large (an overflow),
returns the value “not a number,” which is displayed as NaN. To determine whether a variable has the NaN
value, the predefined predicate function isNaN() must be used. For example, if the variable a has the NaN
value, isNaN(a) returns true.
The Number object has a method, toString, which it inherits from Object but overrides. The toString method
converts the number through which it is called to a string.
This conversion can also be done with the toString method, which has the advantage that it can be given a
parameter to specify the base of the resulting number.
var num = 6;
var str_value = num.toString();
var str_value_binary = num.toString(2);
A number also can be converted to a string by catenating it with the empty string.
Strings can be explicitly converted to numbers in several different ways. One way is with the Number
constructor, as in the following statement:
var number = Number(aString);
The same conversion could be specified by subtracting zero from the string, as in the following statement:
var number = aString - 0;
String methods
7
Note that, for the String methods, character positions start at zero. For example, suppose str has been defined
as follows:
var str = "George";
Then the following expressions have the values shown:
str.charAt(2) is 'o'
str.indexOf('r') is 3
str.substring(2, 4) is 'org'
str.toLowerCase() is 'george'
Assignment Statements
There is a simple assignment operator, denoted by =, and a host of compound assignment operators, such as
+= and /=.
For example, the statement a += 7; means the same as a = a + 7;
The date and time properties of a Date object are in two forms: local and Coordinated Universal Time (UTC),
which was formerly named Greenwich Mean Time.
8
Screen Output and Keyboard Input
The Document object has several properties and methods.
The method, write, is used to create output, which is dynamically created HTML document content.
This content is specified in the parameter of write.
The alert method opens a dialog window and displays its parameter in that window. It also displays an
OK button.
Example of an alert: consider the following code, in which we assume that the value of sum is 42.
9
The confirm method opens a dialog window in which the method displays its string parameter, along
with two buttons: OK and Cancel. confirm returns a Boolean value that indicates the user’s button
input: true for OK and false for Cancel. This method is often used to offer the user the choice of
continuing some process.
var question =
confirm("Do you want to continue this download?");
The prompt method creates a dialog window that contains a text box used to collect a string of input
from the user, which prompt returns as its value. Tthis window also includes two buttons: OK and
Cancel. Prompt takes two parameters: the string that prompts the user for input and a default string in
case the user does not type a string before pressing one of the two buttons.
alert, prompt, and confirm cause the browser to wait for a user response. In the case of alert, the OK
button must be pressed for the JavaScript interpreter to continue. The prompt and confirm methods
wait for either OK or Cancel to be pressed.
Control Statements
A compound statement in JavaScript is a sequence of statements delimited by braces. A control
construct is a control statement together with the statement or compound statement whose execution
it controls.
Control Expressions
The expressions upon which statement flow control can be based include primitive values, relational
expressions, and compound expressions.
The result of evaluating a control expression is one of the Boolean values true and false. If the value of
a
10
control expression is a string, it is interpreted as true unless it is either the empty string ("") or a zero
string ("0"). If the value is a number, it is true unless it is zero (0).
If the special value, NaN, is interpreted as a Boolean, it is false. If undefined is used as a Boolean, it is
false. When interpreted as a Boolean, null is false. When interpreted as a number, true has the value 1
and false has the value 0.
A relational expression has two operands and one relational operator. Table lists the relational
operators.
JavaScript has operators for the AND, OR, and NOT Boolean operations. These are && (AND), || (OR),
and ! (NOT).
Operator precedence and associativity:
Selection Statements
The selection statements are (if-then and if-then-else).
11
The switch Statement
Example:
// borders2.js
// An example of a switch statement for table border size selection
var bordersize;
var err = 0;
bordersize = prompt("Select a table border size: " +
"0 (no border), " +
"1 (1 pixel border), " +
"4 (4 pixel border), " +
"8 (8 pixel border), ");
switch (bordersize) {
case "0": document.write("<table>");
break;
case "1": document.write("<table border = '1'>");
break;
case "4": document.write("<table border = '4'>");
break;
case "8": document.write("<table border = '8'>");
break;
default: {
document.write("Error - invalid choice: ",
bordersize, "<br />");
err = 1;
}}
If (err == 0) {
document.write("<caption> 2010 NFL Divisional",
" Winners </caption>");
document.write("<tr>",
"<th />",
"<th> American Conference </th>",
"<th> National Conference </th>",
"</tr>",
"<tr>",
"<th> East </th>",
"<td> New England Patriots </td>",
"<td> Philadelphia Eagles </td>",
"</tr>",
"<tr>",
12
"<th> North </th>",
"<td> Pittsburgh Steelers </td>",
"<td> Chicago Bears </td>",
"</tr>",
"<tr>",
"<th> West </th>",
"<td> Kansas City Chiefs </td>",
"<td> Seattle Seahawks </td>",
"</tr>",
"<tr>",
"<th> South </th>",
"<td> Indianapolis Colts </td>",
"<td> Atlanta Falcons </td>",
"</tr>",
"</table>");
Loop Statements
While statement:
For statement:
Do-while statement:
13
Example: Date object and a simple for loop
// date.js
// Illustrates the use of the Date object by
// displaying the parts of a current date and
// using two Date objects to time a calculation
// Get the current date
var today = new Date();
// Fetch the various parts of the date
var dateString = today.toLocaleString();
var day = today.getDay();
var month = today.getMonth();
var year = today.getFullYear();
var timeMilliseconds = today.getTime();
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var millisecond = today.getMilliseconds();
// Display the parts
document.write(
"Date: " + dateString + "<br />",
"Day: " + day + "<br />",
"Month: " + month + "<br />",
"Year: " + year + "<br />",
"Time in milliseconds: " + timeMilliseconds + "<br />",
"Hour: " + hour + "<br />",
"Minute: " + minute + "<br />",
"Second: " + second + "<br />",
"Millisecond: " + millisecond + "<br />");
// Time a loop
var dum1 = 1.00149265, product = 1;
var start = new Date();
for (var count = 0; count < 10000; count++)
product = product + 1.000002 * dum1 / 1.00001;
var end = new Date();
var diff = end.getTime() - start.getTime();
document.write("<br />The loop took " + diff + " milliseconds <br />");
14
Object Creation and Modification
The following statement creates an object that has no properties:
var my_object = new Object();
In this case, the constructor called is that of Object, which endows the new object with no properties,
although it does have access to some inherited methods. The variable my_object references the new object.
Calls to constructors must include parentheses, even if there are no parameters.
The properties of an object can be accessed with dot notation, in which the first word is the object name and
the second is the property name. Properties are not actually variables—they are just the names of values.
They are used with object variables to access property values. Because properties are not variables, they are
never declared.
The number of members of a class in Java or C++ is fixed at compile time. The number of properties in a
JavaScript object is dynamic. At any time during interpretation, properties can be added to or deleted from an
object. A property for an object is created by assigning a value to that property’s name. Consider the following
example:
// Create an Object object
var my_car = new Object();
// Create and initialize the make property
my_car.make = "Ford";
// Create and initialize model
my_car.model = "Fusion";
This code creates a new object, my_car, with two properties: make and model.
There is an abbreviated way to create an object and its properties. For example, the object referenced with
my_car in the previous example could be created with the following statement:
var my_car = {make: "Ford", model: "Fusion"};
Notice that this statement includes neither the new operator nor the call to the Object constructor.
Because objects can be nested, you can create a new object that is a property of my_car with properties of its
own, as in the following statements:
15
my_car.engine = new Object();
my_car.engine.config = "V6";
my_car.engine.hp = 263;
Properties can be accessed in two ways. First, any property can be accessed in the same way it is assigned a
value, namely, with the object-dot-property notation. Second, the property names of an object can be
accessed as if they were elements of an array. To do so, the property name (as a string literal) is used as a
subscript.
For example, after execution of the statements
the variables prop1 and prop2 both have the value "Ford".
If an attempt is made to access a property of an object that does not exist, the value undefined is used. A
property can be deleted with delete, as in the following example:
delete my_car.model;
JavaScript has a loop statement, for-in, that is perfect for listing the properties of an object. The form of for-in
is
for (identifier in object)
statement or compound statement
Consider the following example:
for (var prop in my_car)
document.write("Name: ", prop, "; Value: ",
my_car[prop], "<br />");
In this example, the variable, prop, takes on the values of the properties of the my_car object, one for each
iteration. So, this code lists all of the values of the properties of my_car.
Arrays
Array Object Creation
Array objects, unlike most other JavaScript objects, can be created in two distinct ways. The usual way to
create any object is with the new operator and a call to a constructor. In the case of arrays, the constructor is
named Array:
var my_list = new Array(1, 2, "three", "four");
var your_list = new Array(100);
In the first declaration, an Array object of length 4 is created and initialized. Notice that the elements of an
array need not have the same type. In the second declaration, a new Array object of length 100 is created,
without actually creating any elements. Whenever a call to the Array constructor has a single parameter, that
parameter is taken to be the number of elements, not the initial value of a one-element array.
16
The second way to create an Array object is with a literal array value, which is a list of values enclosed in
brackets:
var my_list_2 = [1, 2, "three", "four"];
The array my_list_2 has the same values as the Array object my_list created previously with new.
Array Methods
Array objects have a collection of useful methods. The join method converts all of the elements of an array to
strings and catenates them into a single string. If no parameter is provided to join, the values in the new string
are separated by commas. If a string parameter is provided, it is used as the element separator. Consider the
following example:
var names = new Array["Mary", "Murray", "Murphy", "Max"];
. . .
var name_string = names.join(" : ");
The value of name_string is now "Mary : Murray : Murphy : Max". The reverse method does what you would
expect: It reverses the order of the elements of the Array object through which it is called.
The sort method coerces the elements of the array to become strings if they are not already strings and sorts
them alphabetically. For example, consider the following statement:
names.sort();
The value of names is now ["Mary", "Max", "Murphy", "Murray"].
The concat method catenates its actual parameters to the end of the Array object on which it is called.
Consider the following statements:
var names = new Array["Mary", "Murray", "Murphy", "Max"];
. . .
var new_names = names.concat("Moo", "Meow");
The new_names array now has length 6, with the elements of names, along with "Moo" and "Meow", as its
fifth and sixth elements.
The slice method does for arrays what the substring method does for strings, returning the part of the Array
object specified by its parameters, which are used as subscripts. The array returned has the elements of the
Array object through which it is called, from the first parameter up to, but not including, the second
parameter. For example, consider the following statements:
18
var list = [2, 4, 6, 8, 10];
. . .
var list2 = list.slice(1, 3);
The value of list2 is now [4, 6]. If slice is given just one parameter, the array that is returned has all of the
elements of the object, starting with the specified index. In the following statements
var list = ["Bill", "Will", "Jill", "dill"];
. . .
var listette = list.slice(2);
19
Functions
A function definition consists of the function’s header and a compound statement that describes the actions
of the function. This compound statement is called the body of the function. A function header consists of the
reserved word function, the function’s name, and a parenthesized list of parameters if there are any. The
parentheses are required even if there are no parameters.
A return statement returns control from the function in which it appears to the function’s caller. Optionally, it
includes an expression, whose value is returned to the caller. A function body may include one or more return
statements. If there are no return statements in a function or if the specific return that is executed does not
include an expression, the value returned is undefined. This is also the case if execution reaches the end of the
function body without executing a return statement (an action that is valid).
Syntactically, a call to a function with no parameters states the function’s name followed by an empty pair of
parentheses. A call to a function that returns undefined is a standalone statement. A call to a function that
returns a useful value appears as an operand in an expression (often, the whole right side of an assignment
statement). For example, if fun1 is a parameterless function that returns undefined, and if fun2, which also
has no parameters, returns a useful value, they can be called with the following code:
fun1();
result = fun2();
JavaScript functions are objects, so variables that reference them can be treated as are other object
references—they can be passed as parameters, be assigned to other variables, and be the elements of an
array. The following example is illustrative:
function fun() { document.write(
"This surely is fun! <br/>");}
ref_fun = fun; // Now, ref_fun refers to the fun object
fun(); // A call to fun
ref_fun(); // Also a call to fun
Because JavaScript functions are objects, their references can be properties in other objects, in which case
they act as methods.
Local Variables
The scope of a variable is the range of statements over which it is visible. When JavaScript is embedded in an
HTML document, the scope of a variable is the range of lines of the document over which the variable is
visible.
A variable that is not declared with a var statement is implicitly declared by the JavaScript interpreter at the
time it is first encountered in the script. Variables that are implicitly declared have global scope—that is, they
are visible in the entire HTML document (or entire file if the script is in its own file)—even if the implicit
20
declaration occurs within a function definition. Variables that are explicitly declared outside function
definitions also have global scope. As stated earlier, we recommend that all variables be explicitly declared.
It is usually best for variables that are used only within a function to have local scope, meaning that they are
visible and can be used only within the body of the function. Any variable explicitly declared with var in the
body of a function has local scope.
If a variable that is defined both as a local variable and as a global variable appears in a function, the local
variable has precedence, effectively hiding the global variable with the same name.
This is the advantage of local variables: When you make up their names, you need not be concerned that a
global variable with the same name may exist somewhere in the collection of scripts in the HTML document.
Parameters
The parameter values that appear in a call to a function are called actual parameters. The parameter names
that appear in the header of a function definition, which correspond to the actual parameters in calls to the
function, are called formal parameters.
JavaScript uses the pass-by-value parameter-passing method. When a function is called, the values of the
actual parameters specified in the call are, in effect, copied into their corresponding formal parameters, which
behave exactly like local variables. Because references are passed as the actual parameters of objects, the
called function has access to the objects and can change them, thereby providing the semantics of pass-by-
reference parameters. However, if a reference to an object is passed to a function and the function changes its
corresponding formal parameter (rather than the object to which it points), then the change has no effect on
the actual parameter. For example, suppose an array is passed as a parameter to a function, as in the
following code:
function fun1(my_list) {
var list2 = new Array(1, 3, 5);
my_list[3] = 14;
. . .
my_list = list2;
. . .
}
. . .
var list = new Array(2, 4, 6, 8)
fun1(list);
The first assignment to my_list in fun1 changes the object to which my_list refers, which was created in the
calling code. However, the second assignment to my_list changes it to refer to a different array object. This
does not change the actual parameter in the caller.
Because of JavaScript’s dynamic typing, there is no type checking of parameters. The called function itself can
check the types of parameters with the typeof operator. However, recall that typeof cannot distinguish
between different objects. The number of parameters in a function call is not checked against the number of
formal parameters in the called function. In the function, excess actual parameters that are passed are
ignored; excess formal parameters are set to undefined.
All parameters are communicated through a property array, arguments, that, like other array objects, has a
property named length. By accessing arguments.length, a function can determine the number of actual
21
parameters that were passed. Because the arguments array is directly accessible, all actual parameters
specified in the call are available, including actual parameters that do not correspond to any formal
parameters (because there were more actual parameters than formal parameters). The following example
illustrates a variable number of function parameters:
// params.js
// The params function and a test driver for it.
// This example illustrates a variable number of
// function parameters
// Function params
// Parameters: A variable number of parameters
// Returns: nothing
// Displays its parameters
function params(a, b) {
document.write("Function params was passed ",
arguments.length, " parameter(s) <br />");
document.write("Parameter values are: <br />");
for (var arg = 0; arg < arguments.length; arg++)
document.write(arguments[arg], "<br />");
document.write("<br />");
}
// A test driver for function params
params("Mozart");
params("Mozart", "Beethoven");
params("Mozart", "Beethoven", "Tchaikowsky");
There is no elegant way in JavaScript to pass a primitive value by reference. One inelegant way is to put the
value in an array and pass the array, as in the following script:
// Function by10
// Parameter: a number, passed as the first element
// of an array
// Returns: nothing
// Effect: multiplies the parameter by 10
function by10(a) {
a[0] *= 10;
}
. . .
var x;
var listx = new Array(1);
. . .
22
listx[0] = x;
by10(listx);
x = listx[0];
function by10_2(a) {
return 10 * a;
}
. . .
var x;
. . .
x = by10_2(x);
// Function num_order
// Parameter: Two numbers
// Returns: If the first parameter belongs before the
// second in descending order, a negative number
// If the two parameters are equal, 0
// If the two parameters must be
// interchanged, a positive number
function num_order(a, b) {return b - a;}
// Sort the array of numbers, list, into
// ascending order
num_list.sort(num_order);
Example:
The following example of an HTML document contains a JavaScript function to compute the median of an
array of numbers. The function first uses the sort method to sort the array. If the length of the given array is
odd, the median is the middle element and is determined by dividing the length by 2 and truncating the result
with the use of floor. If the length is even, the median is the average of the two middle elements. Note that
round is used to compute the result of the average computation. Here is the code:
// medians.js
// A function and a function tester
// Illustrates array operations
// Function median
// Parameter: An array of numbers
// Result: The median of the array
// Return value: none
function median(list) {
23
list.sort(function (a, b) {return a - b;});
var list_len = list.length;
// Use the modulus operator to determine whether
// the array's length is odd or even
// Use Math.floor to truncate numbers
// Use Math.round to round numbers
if ((list_len % 2) == 1)
return list[Math.floor(list_len / 2)];
else
return Math.round((list[list_len / 2 - 1] +
list[list_len / 2]) / 2);
} // end of function median
// Test driver
var my_list_1 = [8, 3, 9, 1, 4, 7];
var my_list_2 = [10, -2, 0, 5, 3, 1, 7];
var med = median(my_list_1);
document.write("Median of [", my_list_1, "] is: ",
med, "<br />");
med = median(my_list_2);
document.write("Median of [", my_list_2, "] is: ",
med, "<br />");
Constructors
JavaScript constructors are special functions that create and initialize the properties of newly created objects.
Every new expression must include a call to a constructor whose name is the same as that of the object being
created.
JavaScript has a predefined reference variable for this purpose, named this. When the constructor is called,
this is a reference to the newly created object. The this variable is used to construct and initialize the
properties of the object. For example, the following constructor:
So far, we have considered only data properties. If a method is to be included in the object, it is initialized the
same way as if it were a data property. For example, suppose you wanted a method for car objects that listed
the property values. A function that could serve as such a method could be written as follows:
24
function display_car() {
document.write("Car make: ", this.make, "<br/>");
document.write("Car model: ", this.model, "<br/>");
document.write("Car year: ", this.year, "<br/>");
}
The following line must then be added to the car constructor:
this.display = display_car;
The collection of objects created by using the same constructor is related to the concept of class in an object-
oriented programming language. All such objects have the same set of properties and methods, at least
initially. These objects can diverge from each other through user code changes. Furthermore, there is no
convenient way to determine in the script whether two objects have the same set of properties and methods.
A period matches any character except newline. So, the following pattern matches "snowy",
"snowe", and "snowd", among others:
/snow./
25
To match a period in a string, the period must be preceded by a backslash in the pattern. For
example, the pattern /3\.4/ matches 3.4. The pattern / 3.4/ matches 3.4 and 374, among
others.
It is often convenient to be able to specify classes of characters rather than individual
characters. Such classes are defined by placing the desired characters in brackets. Dashes can
appear in character class definitions, making it easy to specify sequences of characters. For
example, the following character class matches 'a', 'b', or 'c':
[abc]
The following character class matches any lowercase letter from 'a' to 'h':
[a-h]
If a circumflex character (^) is the first character in a class, it inverts the specified set. For
example, the following character class matches any character except the letters 'a', 'e', 'i', 'o',
and 'u':
[^aeiou]
Because they are frequently used, some character classes are predefined and named and can
be specified by their names. These are shown in Table, which gives the names of the classes,
their literal definitions as character classes, and descriptions of what they match.
The following examples show patterns that use predefined character classes:
In many cases, it is convenient to be able to repeat a part of a pattern, often a character or character class. To
repeat a pattern, a numeric quantifier, delimited by braces, is attached. For example, the following pattern
matches
26
xyyyyz:
/xy{4}z/
There are also three symbolic quantifiers: asterisk (*), plus (+), and question mark (?). An asterisk means zero
or more repetitions, a plus sign means one or more repetitions, and a question mark means one or none. For
example, the following pattern matches strings that begin with any number of x’s (including zero), followed by
one or more y’s, possibly followed by z:
/x*y+z?/
The quantifiers are often used with the predefined character-class names, as in the following pattern, which
matches a string of one or more digits followed by a decimal point and possibly more digits:
/\d+\.\d*/
matches the identifiers (a letter, followed by zero or more letters, digits, or underscores) in some
programming languages.
There is one additional named pattern that is often useful: \b (boundary), which matches the boundary
position between a word character (\w) and a nonword character (\W), in either order. For example, the
following pattern matches
The pattern does not match the second string because the “is” is followed by another word character (n).
The boundary pattern is different from the named character classes in that it does not match a character;
instead, it matches a position between two characters.
Anchors
It is useful to be able to specify that a pattern must match at a particular position in a string. The most
common example of this type of specification is requiring a pattern to match at one specific end of the string.
A pattern is tied to a string position with an anchor. A pattern can be specified to match only at the beginning
of the string by preceding it with a circumflex (^) anchor. For example, the following pattern matches "pearls
are pretty" but does not match "My pearls are pretty":
/^pearl/
A pattern can be specified to match at the end of a string only by following the pattern with a dollar sign
anchor. For example, the following pattern matches "I like gold" but does not match "golden":
/gold$/
Anchor characters are like boundary-named patterns: They do not match specific characters in the string;
rather, they match positions before, between, or after characters.
27
Pattern Modifiers
Modifiers can be attached to patterns to change how they are used, thereby increasing their flexibility. The
modifiers are specified as letters just after the right delimiter of the pattern. The i modifier makes the letters
in the pattern match either uppercase or lowercase letters in the string.
For example, the pattern
/Apple/i matches ‘APPLE’, ‘apple’, ‘APPle’, and any other combination of uppercase and lowercase spellings of
the word “apple.”
The x modifier allows white space to appear in the pattern. Because comments are considered white space,
this provides a way to include explanatory comments in the pattern.
For example, the pattern
is equivalent to
/\d+\s[A-Z][a-z]+/
The replace method is used to replace substrings of the String object that match the given pattern. The
replace method takes two parameters: the pattern and the replacement string. The g modifier can be
attached to the pattern if the replacement is to be global in the string, in which case the replacement is done
for every match in the string. The matched substrings of the string are made available through the predefined
variables $1, $2, and so on. For example, consider the following statements:
In this example, str is set to "Boyd, Boyddie, and Boyderica were siblings", and $1, $2, and $3 are all set to
"Fre".
The match method is the most general of the String pattern-matching methods. The match method takes a
single parameter: a pattern. It returns an array of the results of the pattern-matching operation. If the pattern
has the g modifier, the returned array has all of the substrings of the string that matched. If the pattern does
not include the g modifier, the returned array has the match as its first element, and the remainder of the
array has the matches of parenthesized parts of the pattern if there are any:
The following is the value of the matches array after this code is interpreted:
["428 dollars, but I need 500", "428"," dollars, but I need ", "500"]
In this result array, the first element, "428 dollars, but I need 500", is the match; the second, third, and fourth
elements are the parts of the string that matched the parenthesized parts of the pattern, (\d+), ([^\d]+), and
(\d+).
The split method of String splits its object string into substrings on the basis of a given string or pattern. The
substrings are returned in an array. For example, consider the following code:
Example:
// forms_check.js
// A function tst_phone_num is defined and tested.
// This function checks the validity of phone
// number input from a form
// Function tst_phone_num
// Parameter: A string
// Result: Returns true if the parameter has the form of a valid
// seven-digit phone number (3 digits, a dash, 4 digits)
function tst_phone_num(num) {
// Use a simple pattern to check the number of digits and the dash
var ok = num.search(/^\d{3}-\d{4}$/);
if (ok == 0)
return true;
else
return false;
} // end of function tst_phone_num
// A script to test tst_phone_num
var tst = tst_phone_num("444-5432");
if (tst)
document.write("444-5432 is a valid phone number <br />");
else
document.write("Error in tst_phone_num <br />");
tst = tst_phone_num("444-r432");
if (tst)
document.write("Program error <br />");
else
document.write(
"444-r432 is not a valid phone number <br />");
tst = tst_phone_num("44-1234");
if (tst)
document.write("Program error <br />");
29
else
document.write("44-1234 is not a valid phone number <br /");
Errors in Scripts
The JavaScript interpreter is capable of detecting various errors in scripts. These are primarily syntax errors,
although uses of undefined variables are also detected.
Debugging a script is a bit different from debugging a program in a more typical programming language,
mostly because errors that are detected by the JavaScript interpreter are found while the browser is
attempting to display a document. In some cases, a script error causes the browser not to display the
document and does not produce an error message. Without a diagnostic message, you must simply examine
the code to find the problem. For example, consider the following sample script:
// debugdemo.js
// An example to illustrate debugging help
var row;
row = 0;
while(row != 4 {
document.write("row is ", row, "<br />");
row++;
}
Notice the syntax error in the while statement (a missing right parenthesis). Figure shows the browser display
of what happens when an attempt is made to run debugdemo.js.
Write JavaScript scripts for the problems that follow. Write an HTML file that references the JavaScript file.
1. Output: A table of the numbers from 5 to 15 and their squares and cubes, using alert.
<!DOCTYPE html>
<!-- e4_1.html - A solution to Exercise 4.1
-->
<html lang = "en">
<head>
<title> Exercise 4.1 </title>
<meta charset = "utf-8" />
</head>
<body>
30
<script type = "text/javascript">
<!--
var number, square, cube;
document.write("Number, Square, Cube <br /><br />");
for (number = 5; number < 16; number++) {
square = number * number;
cube = number * square;
document.write(number + "…………" + square + "…………" + cube + "<br />");
}
// -->
</script>
</body>
</html>
2. Output: The first 20 Fibonacci numbers, which are defined as in the sequence 1, 1, 2, 3, . . . where each number in the
sequence after the second is the sum of the two previous numbers. You must use document.write to produce the output.
<!DOCTYPE html>
<!-- e4_2.html - A solution to Exercise 4.2
-->
<html lang = "en">
<head>
<title> Exercise 4.2 </title>
<meta charset = "utf-8" />
</head>
<body>
<script type = "text/javascript">
<!--
var first = 1, second = 1, next, count;
document.write("First 20 Fibonacci Numbers <br/><br/>");
document.write("1 - 1 <br/> 2 - 1 <br/>");
for (count = 3; count <= 20; count++) {
next = first + second;
document.write(count + " - " + next + "<br/>");
first = second;
second = next;
}
// -->
</script>
</body>
</html>
31
3. Modify the script of Question 2 to use prompt to input a number n that is the number of the Fibonacci number required
as output.
<!DOCTYPE html>
<!-- e4_4.html - A solution to Exercise 4.4
-->
<html lang = "en">
<head>
<title> Exercise 4.4 </title>
<meta charset = "utf-8" />
</head>
<body>
<script type = "text/javascript">
<!--
var first = 1, second = 1, next, count;
number = prompt("How many Fibonacci numbers do you want? (3-50)", "");
if (number >= 3 && number <= 50) {
document.write("First " + number + " Fibonacci Numbers <br /><br />");
document.write("1 - 1 <br/> 2 - 1 <br />");
32
4. Input: A line of text, using prompt.
Output: The words of the input text, in alphabetical order.
<!DOCTYPE html>
<!-- e4_6.html - A solution to Exercise 4.6
-->
<html lang = "en">
<head>
<title> Exercise 4.6 </title>
<meta charset = "utf-8" />
</head>
<body>
<script type = "text/javascript">
<!--
var first = 1, second = 1, next, count;
33
5. Modify the script of Question 4 to get a second input from the user, which is either "ascending" or "descending". Use
this input to determine how to sort the input words.
<!DOCTYPE html>
<!-- e4_7.html - A solution to Exercise 4.7
-->
<html lang = "en">
<head>
<title> Exercise 4.7 </title>
<meta charset = "utf-8" />
<script type = "text/javascript">
<!--
// A function to compare strings for reverse alphabetic order
function dec_order(a, b) {
if (a > b)
return -1;
else if (a < b)
return 1;
else return 0;
}
// -->
</script>
</head>
<body>
<script type = "text/javascript">
<!--
var order, str, words, word_len, count;
// Get the input
str = prompt("Please input your sentence", "");
order = prompt("What order? (ascending or descending)", "");
// If the order is recognized, issue an error message
if (order != "descending" && order != "ascending")
document.write("Error - order is incorrectly specified <br/>");
// Otherwise, do the sort, depending on the requested order
else {
var words = str.split(" ");
if (order == "ascending")
words = words.sort();
else
words = words.sort(dec_order);
// Write out the results
words_len = words.length;
for (count = 0; count < words_len; count++)
document.write(words[count] + "<br/>");
}
// -->
</script>
</body>
</html>
34
6. Function: e_names
Parameter: An array of names, represented as strings.
Returns: The number of names in the given array that end in either "ie" or "y".
<!DOCTYPE html>
<!-- e4_9.html - A solution to Exercise 4.9
-->
<html lang = "en">
<head>
<title> Exercise 4.9 </title>
<meta charset = "utf-8" />
<script type = "text/javascript">
<!--
// Function e_names
// Parameter: an array of strings
// Returns: the number of given strings that end
// in either "ie" or "y"
function e_names(names) {
var len, index, count = 0;
len = names.length;
7. Function: reverser
Parameter: A number.
Returns: The number with its digits in reverse order.
// Function reverser
// Parameter: a number
// Returns: the number with its digits in reverse order
// Note: Math.floor must be used to get the integer part
// of the division operations
function reverser(num) {
var digit, position = 0;
36
}
// -->
</script>
</head>
<body>
<script type = "text/javascript">
<!--
// Function reverser tester
var num1 = 2468, num2 = 7;
result = reverser(num1);
document.write("The reverse of 2468 is: " + result + "<br />");
result = reverser(num2);
document.write("The reverse of 7 is: " + result + "<br />");
// -->
</script>
</body>
</html>
37
Event Handling
Detect certain activities of the browser and the browser user and provide computation when those
activities occur. These computations are specified with a special form of programming called event-
driven programming.
In event-driven programming, parts of the program are executed at completely unpredictable times,
often triggered by user interactions with the program that is executing.
An event is a notification that something specific has occurred, either in the browser, such as the
completion of the loading of a document, or a browser user action, such as a mouse click on a form
button. Strictly speaking, an event is an object that is implicitly created by the browser and the
JavaScript system in response to something having happened.
An event handler is a script that is implicitly executed in response to the appearance of an event. Event
handlers enable a Web document to be responsive to browser and user activities. One of the most
common uses of event handlers is to check for simple errors and omissions in user input to the elements
of a form, either when they are changed or when the form is submitted. This kind of checking saves the
time of sending incorrect form data to the server.
Events are created by activities associated with specific HTML elements. For example, the click event
can be caused by the browser user clicking a radio button or the link of an anchor tag, among other
things.
The process of connecting an event handler to an event is called registration. There are two distinct
approaches to event handler registration, one that assigns tag attributes and one that assigns handler
addresses to object properties.
38
An HTML element is said to get focus when the user puts the mouse cursor over it and clicks the left mouse button. An element can
also get focus when the user tabs to the element. When a text element has focus, any keyboard input goes into that element.
Obviously, only one text element can have focus at one time. An element becomes blurred when the user moves the cursor away from
the element and clicks the left mouse button or when the user tabs away from the element. An element obviously becomes blurred
when another element gets focus. Several nontext elements can also have focus, but the condition is less useful in those cases.
39
<input type = "button" id = "myButton" onclick = "alert('You clicked my button!');" />
In many cases, the handler consists of more than a single statement. In these cases, often a function is used and the literal string value
of the attribute is the call to the function.
40
An event handler function could also be registered by assigning its name to the associated event property on the button object, as in
the following example:
document.getElementById("myButton").onclick = myButtonHandler;
HTML:
<!DOCTYPE html>
<!-- load.html
A document for load.js
-->
<html lang = "en">
<head>
<title> load.html </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "load.js" >
</script>
</head>
<body onload="load_greeting();">
<p />
</body>
</html>
Js file:
// load.js
// An example to illustrate the load event
// The onload event handler
function load_greeting () {
alert("You are visiting the home page of \n" +
"Pete's Pickled Peppers \n" + "WELCOME!!!");
}
JS FILE:
// radio_click.js
// An example of the use of the click event with radio buttons,
// registering the event handler by assignment to the button
// attributes
// The event handler for a radio button collection
function planeChoice (plane) {
// Produce an alert message about the chosen airplane
switch (plane) {
case 152:
alert("A small two-place airplane for flight training");
break;
case 172:
alert("The smaller of two four-place airplanes");
break;
case 182:
alert("The larger of two four-place airplanes");
break;
case 210:
alert("A six-place high-performance airplane");
break;
default:
alert("Error in JavaScript function planeChoice");
break;
}
}
42
Handling Events from Text Box and Password Elements
Text boxes and passwords can create four different events: blur, focus, change, and select.
HTML file:
<!DOCTYPE html>
<!-- nochange.html
A document for nochange.js
-->
<html lang = "en">
<head>
<title> nochange.html </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "nochange.js" >
</script>
<style type = "text/css">
td, th, table {border: thin solid black}
</style>
</head>
<body>
<form action = "">
<h3> Coffee Order Form </h3>
<!-- A bordered table for item orders -->
<table>
<!-- First, the column headings -->
<tr>
<th> Product Name </th>
<th> Price </th>
<th> Quantity </th>
</tr>
<!-- Now, the table data entries -->
<tr>
<th> French Vanilla (1 lb.) </th>
<td> $3.49 </td>
<td> <input type = "text" id = "french"
size ="2" /> </td>
</tr>
<tr>
<th> Hazlenut Cream (1 lb.) </th>
<td> $3.95 </td>
43
<td> <input type = "text" id = "hazlenut"
size = "2" /> </td>
</tr>
<tr>
<th> Colombian (1 lb.) </th>
<td> $4.59 </td>
<td> <input type = "text" id = "colombian"
size = "2" /></td>
</tr>
</table>
<!-- Button for precomputation of the total cost -->
<p>
<input type = "button" value = "Total Cost"
onclick = "computeCost();" />
<input type = "text" size = "5" id = "cost"
onfocus = "this.blur();" />
</p>
<!-- The submit and reset buttons -->
<p>
<input type = "submit" value = "Submit Order" />
<input type = "reset" value = "Clear Order Form" />
</p>
</form>
</body>
</html>
JS file:event handler
// pswd_chk.js
// An example of input password checking using the submit
// event
// The event handler function for password checking
function chkPasswords() {
var init = document.getElementById("initial");
var sec = document.getElementById("second");
if (init.value == "") {
alert("You did not enter a password \n" +
"Please enter one now");
return false;
}
if (init.value != sec.value) {
alert("The two passwords you entered are not the same \n" +
"Please re-enter both now");
return false;
} else
return true;
}
JS file:event registration
// pswd_chkr.js
// Register the event handlers for pswd_chk.html
document.getElementById("second").onblur = chkPasswords;
document.getElementById("myForm").onsubmit = chkPasswords;
45
Error:
46
function chkName() {
var myName = document.getElementById("custName");
// Test the format of the input name
// Allow the spaces after the commas to be optional
// Allow the period after the initial to be optional
var pos = myName.value.search(
/^[A-Z][a-z]+, ?[A-Z][a-z]+, ?[A-Z]\.?$/);
if (pos != 0) {
alert("The name you entered (" + myName.value +
") is not in the correct form. \n" +
"The correct form is:" +
"last-name, first-name, middle-initial \n" +
"Please go back and fix your name");
return false;
} else
return true;
}
// The event handler function for the phone number text box
function chkPhone() {
var myPhone = document.getElementById("phone");
// Test the format of the input phone number
var pos = myPhone.value.search(/^\d{3}-\d{3}-\d{4}$/);
if (pos != 0) {
alert("The phone number you entered (" + myPhone.value +
") is not in the correct form. \n" +
"The correct form is: ddd-ddd-dddd \n" +
"Please go back and fix your phone number");
return false;
} else
return true;
}
JS file: event registration
// validatorr.js
// Register the event handlers for validator.html
document.getElementById("custName").onchange = chkName;
document.getElementById("phone").onchange = chkPhone;
Error:
Error:
47
1. The document must display an image and three buttons. The buttons should be labeled simply 1, 2, and 3.
When pressed, each button should change the content of the image to that of a different image.
<html>
<head>
</head>
<body>
<!--On button click changeImg() will be call-->
<input type="button" onclick="changeImg(1)" value="1"/>
<input type="button" onclick="changeImg(2)" value="2"/>
<input type="button" onclick="changeImg(3)" value="3"/><br><br>
<img id="photo" src="b.jpg" width="300" height="200"/>
</body>
<script>
// if x ==1 than image one will be display
function changeImg(x)
{ if(x==1)
{
document.getElementById("photo").src="b.jpg";
}
else if(x==2) // if x ==2 than image Second will be display
{
document.getElementById("photo").src="c.jpg";
}
else // if x ==3 than image third will be display
{
document.getElementById("photo").src="d.jpg";
}
}
</script>
</html>
<!DOCTYPE html>
<html>
<head>
<title> Exercise for substr and substring functions of string</title>
</head>
<body>
<script type="text/javascript">
49
<!--
var str="Bangalore";
document.write("substr function on string Bangalore (1,4) is: "+str.substr(1,4)+"<br />");
document.write("substring function on string Bangalore (1,4) is: "+str.substring(1,4));
//-->
</script>
</body>
</html>
50
7. JavaScript script to find Largest of three numbers
<!DOCTYPE html>
<html> <body>
<script type="text/javascript">
{
var n1=Number(prompt("Enter number 1: "));
var n2=Number(prompt("Enter number 2: "));
var n3=Number(prompt("Enter number 3: "));
if (n1>n2 && n1>n3)
alert(n1+" is largest");
else if(n2>n3)
alert(n2+" is largest");
else
alert(n3+" is largest");
}
</script>
</body>
</html>
9. Program to find the number of negative values, zeros and values greater than Zeros in the given array.
<body>
<script type="text/javascript">
var list = [2, 10, -4, 0, 8,-6,0, 21];
var i,pos=0,neg=0,zeros=0;
document.write("Elements of Array","<br />");
for(i=0;i<list.length;i++)
document.write(list[i]+" ");
document.write("<br /><br />");
for(i=0;i<list.length;i++) {
if(Number(list[i])>0)
pos++;
else if(Number(list[i])<0)
neg++;
else
zeros++;
}
document.write("Number of Positive Numbers:",pos,"<br / >");
document.write("Number of Negative Numbers: ",neg,"<br / >");
document.write("Number of Zeros: ",zeros,"<br / >");
</script>
</body>
53
const case6 = arr.slice(3, -2);
document.write("Case 6: Negative end index: ", case6,"<br />");
// Case 9: Start and end index are negative and out of range
const case9 = arr.slice(-15, -10);
document.write("Case 9: Start and end index are negative" + " and out of range: ", case9);
</script>
</body>
</html>
54
13. Example for function:
<html>
<head>
</head>
<body>
<script type="text/javascript">
var a,b,c;
a=10; b=20;
//actual parameters a and b
c=sum(a,b);
document.write("Total :",c);
14. Write JavaScript function which accepts input from user a string and prints the position of the leftmost
vowel (first vowel).
<html> <head></head ><body> <script type="text/javascript">
//function to print the position of the leftmost vowel in the string
function firstvowel(){
var find = 0,pos,i; var str=prompt("Enter the string: ");
str=str.toLowerCase();
for(i=0;i<str.length;i++)
{
if(str[i]=='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u')
{
55
find=1; pos=i; break;
}
}
if(find)
document.write("Position of first vowel in the string ", str, " was ",(pos+1));
else
document.write("Vowel Not found");
return;
}
document.write("Function to find first vowel in a String","<br />");
firstvowel(); </script> </body> </html>
15. Write a program check validity of the USN of the format 1BM19IS followed by three digits.
Example:
Valid: 1BM19IS065, 1bm19is999
Not Valid: 1BM18IS6 , 1BM17IS038, 1is16BM065
Note: Accept the USN from the user through textbox.
<html>
<head>
<script type="text/javascript">
function validate() {
strValidate=strForm.str.value.search(/1BM19IS[0-9]{3}/i);
if(strValidate== -1) {
alert("Not Valid");
} else
alert("Valid"); }
</script> </head>
<body>
<form name="strForm" onsubmit="validate();">
<label> <b> Enter USN </b> </label>
<input type="text" name="str"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
56
16. Write a Regular Expression to validate ten digit mobile number
Example:
Valid: 8762742909, 9448444160
Not Valid: 84441604, 762742909
<html>
<head>
<script type="text/javascript">
function validate() {
strValidate=strForm.str.value.search(/[0-9]{10}/);
if(strValidate== -1) {
alert("Not Valid");
}
alert("Valid");
}
</script>
</head>
<body>
<form name="strForm" onsubmit="validate();">
<label> <b> Enter Mobile Number </b> </label>
<input type="text" name="str"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
57