0% found this document useful (0 votes)
6 views64 pages

Unit II

The document outlines the curriculum for a Web Technologies course at Vardhaman College of Engineering, focusing on JavaScript and XML. It covers topics such as JavaScript variables, operators, control statements, functions, and data types, as well as XML basics including DTD and XML Schema. The document includes examples and explanations of various JavaScript concepts and their applications in web development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views64 pages

Unit II

The document outlines the curriculum for a Web Technologies course at Vardhaman College of Engineering, focusing on JavaScript and XML. It covers topics such as JavaScript variables, operators, control statements, functions, and data types, as well as XML basics including DTD and XML Schema. The document includes examples and explanations of various JavaScript concepts and their applications in web development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

VARDHAMAN COLLGE OF ENGINEERING

Department of Information Technology


III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

UNIT II

Javascript and XML: Introduction to JavaScript and Client-Side Scripting, Java Script-
Variables, Operators, Control Statements and Functions. Java Script Objects- Strings, Arrays,
Date, Math, RegExp, Event handling, Java Script Error handling and Validations, XML:
Introduction to XML, DTD, XML Schema, XSLT, DOM and SAX parsers.
1. Introduction to JavaScript

JavaScript is the world's most popular programming language.

JavaScript is the programming language of the Web.

JavaScript Can Change HTML Content

One of many JavaScript HTML methods is getElementById().

The example below "finds" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":

document.getElementById("demo").innerHTML = "Hello JavaScript";

JavaScript Can Change HTML Attribute Values

In this example JavaScript changes the value of the src (source) attribute of
an <img> tag:

JavaScript Can Change HTML Styles (CSS)

Changing the style of an HTML element, is a variant of changing an HTML attribute:

document.getElementById("demo").style.fontSize = "35px";

JavaScript Display Possibilities


JavaScript can "display" data in different ways:
 Writing into an HTML element, using innerHTML.
 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().
Using innerHTML

To access an HTML element, JavaScript can use the document.getElementById(id) method.

1
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

The id attribute defines the HTML element. The innerHTML property defines the HTML
content:
Example

<!DOCTYPE html>

<html>

<body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;

</script>
</body>

</html>

Using document.write()
For testing purposes, it is convenient to use document.write():

Example

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>

Using window.alert()
You can use an alert box to display data:

Example

2
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>

You can skip the window keyword.

In JavaScript, the window object is the global scope object. This means that variables,
properties, and methods by default belong to the window object. This also means that
specifying the window keyword is optional:

Example

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
alert(5 + 6);
</script>
</body>
</html>

Using console.log()
For debugging purposes, you can call the console.log() method in the browser to display
data.

You will learn more about debugging in a later chapter.


Example

<!DOCTYPE html>
<html>
<body>

3
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<script>
console.log(5 + 6);
</script>
</body>
</html>

JAVASCRIPT VARIABLES
Variables are Containers for Storing Data

JavaScript Variables can be declared in 4 ways:

Automatically

Using var

Using let

Using const
Note

The var keyword was used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.


The var keyword should only be used in code written for older browsers.

When to Use var, let, or const?


1. Always declare variables

2. Always use const if the value should not be changed

3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you can't use const

5. Only use var if you MUST support old browsers.

JavaScript Data Types


JavaScript variables can hold numbers like 100 and text values like "John Doe".
In programming, text values are called text strings.
JavaScript can handle many types of data, but for now, just think of numbers and strings.

Strings are written inside double or single quotes. Numbers are written without quotes.

If you put a number in quotes, it will be treated as a text string.

4
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

Example

const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';

Declaring a JavaScript Variable

Creating a variable in JavaScript is called "declaring" a variable.


You declare a JavaScript variable with the var or the let keyword:
var carName;

Types of JavaScript Operators


There are different types of JavaScript operators:

 Arithmetic Operators
 Assignment Operators

 Comparison Operators
 String Operators

 Logical Operators
 Bitwise Operators
 Ternary Operators

 Type Operators

JavaScript Arithmetic Operators


Arithmetic Operators are used to perform arithmetic on numbers:
Arithmetic Operators Example

let a = 3;
let x = (100 + 50) * a;
EXAMPLE

<!DOCTYPE html>

<html lang="en">

5
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<head>

<title>JavaScript Arithmetic Operators</title>

</head>

<body>

<script>
// Declare variables

let a = 10;
let b = 3;

// Arithmetic operations

let addition = a + b; // Addition: 10 + 3

let subtraction = a - b; // Subtraction: 10 - 3


let multiplication = a * b; // Multiplication: 10 * 3
let division = a / b; // Division: 10 / 3

let modulus = a % b; // Modulus: 10 % 3


let exponentiation = a ** b; // Exponentiation: 10^3

// Display the results using document.write()


document.write('Addition: ' + addition + '<br>');

document.write('Subtraction: ' + subtraction + '<br>');


document.write('Multiplication: ' + multiplication + '<br>');
document.write('Division: ' + division + '<br>');

document.write('Modulus: ' + modulus + '<br>');

document.write('Exponentiation: ' + exponentiation + '<br>');

</script>
</body>

</html>

JavaScript Assignment Operators


Assignment operators assign values to JavaScript variables.

6
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

The Addition Assignment Operator (+=) adds a value to a variable.

Assignment

let x = 10;
x += 5;

EXAMPLE

<!DOCTYPE html>

<html lang="en">
<body>

<h2>Assignment Operators Example</h2>

<script>
// Declare variables

let x = 10;
let y = 5;

// Basic assignment
let z = x; // z = 10

// Assignment with addition


x += y; // x = x + y => 10 + 5 = 15

// Assignment with subtraction

y -= 2; // y = y - 2 => 5 - 2 = 3
// Assignment with multiplication

z *= 2; // z = z * 2 => 10 * 2 = 20
// Assignment with division

x /= 5; // x = x / 5 => 15 / 5 = 3
// Assignment with modulus

y %= 2; // y = y % 2 => 3 % 2 = 1

// Assignment with exponentiation

z **= 2; // z = z ** 2 => 20 ** 2 = 400

// Displaying results using document.write()

7
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

document.write("x = " + x + "<br>"); // x = 3

document.write("y = " + y + "<br>"); // y = 1

document.write("z = " + z + "<br>"); // z = 400

</script>

</body>
</html>

JavaScript Comparison Operators

Operator Description

== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

> greater than

< less than

>= greater than or equal to

<= less than or equal to

? ternary operator

EXAMPLE
<!DOCTYPE html>

<html lang="en">

<head>
<title>JavaScript Comparison Operators</title>

</head>

8
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<body>

<h2>Comparison Operators Example</h2>

<script>

// Declare variables

let a = 10;
let b = 20;

// Comparison operators
let equal = (a == b); // Equal to

let notEqual = (a != b); // Not equal to

let strictlyEqual = (a === b); // Strictly equal to (checks both value and type)

let greaterThan = (a > b); // Greater than


let lessThan = (a < b); // Less than
let greaterOrEqual = (a >= b); // Greater than or equal to

let lessOrEqual = (a <= b); // Less than or equal to


// Displaying results using document.write()

document.write("a == b: " + equal + "<br>"); // false


document.write("a != b: " + notEqual + "<br>"); // true

document.write("a === b: " + strictlyEqual + "<br>"); // false


document.write("a > b: " + greaterThan + "<br>"); // false
document.write("a < b: " + lessThan + "<br>"); // true

document.write("a >= b: " + greaterOrEqual + "<br>"); // false

document.write("a <= b: " + lessOrEqual + "<br>"); // true

</script>
</body>

</html>

9
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

JavaScript Logical Operators

Operator Description

&& logical and

|| logical or

! logical not

EXAMPLE

<!DOCTYPE html>
<html lang="en">

<head>

<title>JavaScript Logical Operators</title>

</head>

<body>
<h2>Logical Operators Example</h2>

<script>

// Declare variables
let a = true;

let b = false;
// Logical operators

let andOperator = a && b; // Logical AND


let orOperator = a || b; // Logical OR

let notOperatorA = !a; // Logical NOT on a


let notOperatorB = !b; // Logical NOT on b
// Displaying results using document.write()

document.write("a && b: " + andOperator + "<br>"); // false

document.write("a || b: " + orOperator + "<br>"); // true

document.write("!a: " + notOperatorA + "<br>"); // false

10
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

document.write("!b: " + notOperatorB + "<br>"); // true

</script>

</body>

</html>

JavaScript Logical Operators

Operator Description

&& logical and

|| logical or

! logical not
EXAMPLE
<!DOCTYPE html>
<html lang="en">

<head>
<title>JavaScript Logical Operators</title>

</head>
<body>

<h2>Logical Operators Example</h2>

<script>
// Declare variables

let x = 5;
let y = 10;

let z = 0;
// Logical AND (&&)
let andOperator1 = (x > 0 && y > 0); // true && true = true

let andOperator2 = (x > 0 && z > 0); // true && false = false

11
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

// Logical OR (||)

let orOperator1 = (x > 0 || z > 0); // true || false = true

let orOperator2 = (z > 0 || y > 0); // false || true = true

// Logical NOT (!)

let notOperator1 = !(x > 0); // !true = false


let notOperator2 = !(z > 0); // !false = true

// Displaying results using document.write()


document.write("x > 0 && y > 0: " + andOperator1 + "<br>"); // true

document.write("x > 0 && z > 0: " + andOperator2 + "<br>"); // false

document.write("x > 0 || z > 0: " + orOperator1 + "<br>"); // true

document.write("z > 0 || y > 0: " + orOperator2 + "<br>"); // true


document.write("!(x > 0): " + notOperator1 + "<br>"); // false
document.write("!(z > 0): " + notOperator2 + "<br>"); // true

</script>
</body>

</html>
CONTROL STATEMENTS

1. if, else if, else Statements


<!DOCTYPE html>
<html lang="en">

<head>

<title>JavaScript Control Statements</title>

</head>
<body>

<h2>If, Else If, Else Example</h2>


<script>

let age = 25;

12
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

// if, else if, else example

if (age < 18) {

document.write("You are a minor.<br>");

} else if (age >= 18 && age < 60) {


document.write("You are an adult.<br>");

} else {
document.write("You are a senior citizen.<br>");

</script>

</body>
</html>
2. switch Statement

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">


<title>JavaScript Control Statements</title>
</head>

<body>

<h2>Switch Statement Example</h2>

<script>
let day = 3;

// switch example
switch(day) {

case 1:

13
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

document.write("Today is Monday.<br>");

break;

case 2:

document.write("Today is Tuesday.<br>");

break;
case 3:

document.write("Today is Wednesday.<br>");
break;

case 4:

document.write("Today is Thursday.<br>");

break;
case 5:
document.write("Today is Friday.<br>");

break;
default:

document.write("It's the weekend!<br>");


}

</script>
</body>
</html>

3. for Loop
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Control Statements</title>
</head>
<body>

<h2>For Loop Example</h2>

14
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<script>
// for loop example
for (let i = 1; i <= 5; i++) {
document.write("Number: " + i + "<br>");
}
</script>
</body>
</html>
4. while Loop
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Control Statements</title>
</head>
<body>

<h2>While Loop Example</h2>

<script>
let i = 1;

// while loop example


while (i <= 5) {
document.write("Number: " + i + "<br>");
i++;
}
</script>

</body>
</html>
5. do...while Loop
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Control Statements</title>
</head>

15
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<body>

<h2>Do...While Loop Example</h2>

<script>
let j = 1;

// do...while loop example


do {
document.write("Number: " + j + "<br>");
j++;
} while (j <= 5);
</script>
</body>
</html>

6. break and continue


<!DOCTYPE html>

<html lang="en">
<head>

<title>JavaScript Control Statements</title>

</head>
<body>

<h2>Break and Continue Example</h2>


<script>

// break example: stop loop when i equals 3

for (let i = 1; i <= 5; i++) {

if (i === 3) {

break;
}

document.write("Number: " + i + " (before break)<br>");


}

16
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

document.write("<br>");

// continue example: skip loop when i equals 3

for (let i = 1; i <= 5; i++) {

if (i === 3) {

continue;
}

document.write("Number: " + i + " (after continue)<br>");


}

</script>

</body>

</html>

JAVASCRIPT FUNCTIONS

A JavaScript function is a block of code designed to perform a particular task.


A JavaScript function is executed when "something" invokes it (calls it).

JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}


function name(parameter1, parameter2, parameter3) {
// code to be executed
}

17
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

EXAMPLE

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>JavaScript Function Example</title>


</head>

<body>

<h2>JavaScript Function Example</h2>

<script>
// Defining a simple function
function greet(name) {

return "Hello, " + name + "!";


}

// Calling the function and displaying the result


let result = greet("Swapna");

document.write(result); // Output: Hello, Swapna!


</script>
</body>

</html>

OBJECTS
JavaScript Objects
Objects are variables too. But objects can contain many values.

This code assigns many values (Fiat, 500, white) to an object named car:
Example

const car = {type:"Fiat", model:"500", color:"white"};

18
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

How to Define a JavaScript Object

 Using an Object Literal

 Using the new Keyword

 Using an Object Constructor

1) JavaScript Object by object literal


The syntax of creating object using object literal is given below:

1. object={property1:value1,property2:value2.....propertyN:valueN}
As you can see, property and value is separated by : (colon).

Let’s see the simple example of creating object in JavaScript.

<script>

emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

2) By creating instance of Object

The syntax of creating object directly is given below:


1. var objectname=new Object();

Here, new keyword is used to create object.


Let’s see the example of creating object directly.
<script>

var emp=new Object();

emp.id=101;

emp.name="Ravi Malik";
emp.salary=50000;

document.write(emp.id+" "+emp.name+" "+emp.salary);


</script>

3) By using an Object constructor

19
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

Here, you need to create function with arguments. Each argument value can be assigned
in the current object by using this keyword.
The this keyword refers to the current object.

The example of creating object by object constructor is given below.

<script>

function emp(id,name,salary){

this.id=id;
this.name=name;

this.salary=salary;

}
e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);

</script>
There are 3 ways to construct array in JavaScript

1. By array literal
2. By creating instance of Array directly (using new keyword)

3. By using an Array constructor (using new keyword)

1) JavaScript array literal


The syntax of creating array using array literal is given below:

1. var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).

Let's see the simple example of creating and using array in JavaScript.
<script>

var emp=["Sonoo","Vimal","Ratan"];

for (i=0;i<emp.length;i++){

document.write(emp[i] + "<br/>");

20
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

</script>

2) JavaScript Array directly (new keyword)

The syntax of creating array directly is given below:

1. var arrayname=new Array();

Here, new keyword is used to create instance of array.


Let's see the example of creating array directly.

<script>
var i;

var emp = new Array();

emp[0] = "Arun";

emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");

}
</script>

3) JavaScript array constructor (new keyword)


Here, you need to create instance of array by passing arguments in constructor so that we
don't have to provide value explicitly.

The example of creating object by array constructor is given below.


<script>

var emp=new Array("Jai","Vijay","Smith");


for (i=0;i<emp.length;i++){

document.write(emp[i] + "<br>");

</script>

JavaScript Array Methods

21
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

Let's see the list of JavaScript array methods with their description.

Methods Description

It returns a new array object that contains two or more


concat()
merged arrays.

It copies the part of the given array with its own elements
copywithin()
and returns the modified array.

It creates an iterator object and a loop that iterates over


entries()
each key/value pair.

It determines whether all the elements of an array are


every()
satisfying the provided function conditions.

It creates a new array carrying sub-array elements


flat()
concatenated recursively till the specified depth.

It maps all array elements via mapping function, then


flatMap()
flattens the result into a new array.

fill() It fills elements into an array with static values.

It creates a new array carrying the exact copy of another


from()
array element.

It returns the new array containing the elements that


filter()
pass the provided function conditions.

It returns the value of the first element in the given array


find()
that satisfies the specified condition.

It returns the index value of the first element in the given


findIndex()
array that satisfies the specified condition.

It invokes the provided function once for each element of


forEach()
an array.

It checks whether the given array contains the specified


includes()
element.

It searches the specified element in the given array and


indexOf()
returns the index of the first match.

22
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

isArray() It tests if the passed value ia an array.

join() It joins the elements of an array as a string.

It creates an iterator object that contains only the keys of


keys()
the array, then loops through these keys.

It searches the specified element in the given array and


lastIndexOf()
returns the index of the last match.

It calls the specified function for every array element and


map()
returns the new array

It creates a new array from a variable number of


of()
arguments, holding any type of argument.

pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

reduce(function, It executes a provided function for each value from left to


initial) right and reduces the array to a single value.

It executes a provided function for each value from right


reduceRight()
to left and reduces the array to a single value.

It determines if any element of the array passes the test


some()
of the implemented function.

shift() It removes and returns the first element of an array.

It returns a new array containing the copy of the part of


slice()
the given array.

sort() It returns the element of the given array in a sorted order.

splice() It add/remove elements to/from the given array.

It returns a string containing all the elements of a


toLocaleString()
specified array.

23
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

It converts the elements of a specified array into string


toString()
form, without affecting the original array.

It adds one or more elements in the beginning of the


unshift()
given array.

It creates a new iterator object carrying values for each


values()
index in the array.

EXAMPLE
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Arrays Example</title>
</head>
<body>
<h2>JavaScript Arrays Example</h2>
<script>
// Creating an array
let fruits = ["Apple", "Banana", "Cherry", "Date"];
// Accessing array elements
let firstFruit = fruits[0]; // "Apple"
let secondFruit = fruits[1]; // "Banana"
// Adding an element to the array
fruits.push("Elderberry"); // Adds "Elderberry" to the end of the array
// Removing the last element from the array
let lastFruit = fruits.pop(); // Removes "Elderberry" from the end
// Adding an element to the beginning of the array
fruits.unshift("Fig"); // Adds "Fig" to the beginning of the array
// Removing the first element from the array
let removedFruit = fruits.shift(); // Removes "Fig" from the beginning
// Finding the index of an element
let indexOfCherry = fruits.indexOf("Cherry"); // Finds the index of "Cherry"
// Slicing the array
let slicedFruits = fruits.slice(1, 3); // Extracts elements from index 1 to 2
// Displaying results using document.write()
document.write("Original Array: " + fruits.join(", ") + "<br>");
document.write("First Fruit: " + firstFruit + "<br>");
document.write("Second Fruit: " + secondFruit + "<br>");
document.write("Added 'Elderberry' to the array.<br>");

24
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

document.write("Removed last fruit: " + lastFruit + "<br>");


document.write("Added 'Fig' to the beginning of the array.<br>");
document.write("Removed first fruit: " + removedFruit + "<br>");
document.write("Index of 'Cherry': " + indexOfCherry + "<br>");
document.write("Sliced Array (index 1 to 2): " + slicedFruits.join(", ") + "<br>");
</script>
</body>
</html>
JavaScript String
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
1. By string literal
2. By string object (using new keyword)

1) By string literal
The string literal is created using double quotes. The syntax of creating string using
string literal is given below:
var stringname="string value";

<script>
var str="This is string literal";

document.write(str);

</script>
2) By string object (using new keyword)

The syntax of creating string object using new keyword is given below:
var stringname=new String("string literal");
Here, new keyword is used to create instance of string.
Let's see the example of creating string in JavaScript by new keyword.
<script>

var stringname=new String("hello javascript string");


document.write(stringname);
</script>

JavaScript String Methods example


<!DOCTYPE html>
<html lang="en">

25
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<head>
<title>JavaScript String Handling Functions</title>
</head>
<body>
<h2>JavaScript String Handling Functions Example</h2>
<script>
// Declare a string
let str = "Hello, JavaScript!";
// String length
let strLength = str.length;
// Convert to uppercase
let upperStr = str.toUpperCase();
// Convert to lowercase
let lowerStr = str.toLowerCase();
// Find a substring
let subStr = str.substring(7, 17); // Extract "JavaScript"
// Replace a part of the string
let newStr = str.replace("JavaScript", "World");
// Concatenation
let greeting = "Welcome to ";
let combinedStr = greeting.concat(str);
// Display results using document.write()
document.write("Original String: " + str + "<br>");
document.write("String Length: " + strLength + "<br>");
document.write("Uppercase String: " + upperStr + "<br>");
document.write("Lowercase String: " + lowerStr + "<br>");
document.write("Substring (7, 17): " + subStr + "<br>");
document.write("Replaced String: " + newStr + "<br>");
document.write("Concatenated String: " + combinedStr + "<br>");
</script>
</body>
</html>

DATE OBJECT
JavaScript Date Object
The JavaScript date object can be used to get year, month and day. You can display a
timer on the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods to
get and set day, month, year, hour, minute and seconds.
Constructor

26
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

You can use 4 variant of Date constructor to create date object.

Date()

Date(milliseconds)

Date(dateString)

Date(year, month, day, hours, minutes, seconds, milliseconds)

Methods Description

It returns the integer value between 1 and 31


getDate() that represents the day for the specified date on
the basis of local time.

It returns the integer value between 0 and 6 that


getDay() represents the day of the week on the basis of
local time.

It returns the integer value that represents the


getFullYears()
year on the basis of local time.

It returns the integer value between 0 and 23


getHours() that represents the hours on the basis of local
time.

It returns the integer value between 0 and 999


getMilliseconds() that represents the milliseconds on the basis of
local time.

It returns the integer value between 0 and 59


getMinutes() that represents the minutes on the basis of local
time.

It returns the integer value between 0 and 11


getMonth() that represents the month on the basis of local
time.

It returns the integer value between 0 and 60


getSeconds() that represents the seconds on the basis of local
time.

27
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

It returns the integer value between 1 and 31


getUTCDate() that represents the day for the specified date on
the basis of universal time.

It returns the integer value between 0 and 6 that


getUTCDay() represents the day of the week on the basis of
universal time.

It returns the integer value that represents the


getUTCFullYears()
year on the basis of universal time.

It returns the integer value between 0 and 23


getUTCHours() that represents the hours on the basis of
universal time.

It returns the integer value between 0 and 59


getUTCMinutes() that represents the minutes on the basis of
universal time.

It returns the integer value between 0 and 11


getUTCMonth() that represents the month on the basis of
universal time.

It returns the integer value between 0 and 60


getUTCSeconds() that represents the seconds on the basis of
universal time.

It sets the day value for the specified date on the


setDate()
basis of local time.

It sets the particular day of the week on the basis


setDay()
of local time.

It sets the year value for the specified date on


setFullYears()
the basis of local time.

It sets the hour value for the specified date on


setHours()
the basis of local time.

It sets the millisecond value for the specified


setMilliseconds()
date on the basis of local time.

28
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

It sets the minute value for the specified date on


setMinutes()
the basis of local time.

It sets the month value for the specified date on


setMonth()
the basis of local time.

It sets the second value for the specified date on


setSeconds()
the basis of local time.

It sets the day value for the specified date on the


setUTCDate()
basis of universal time.

It sets the particular day of the week on the basis


setUTCDay()
of universal time.

It sets the year value for the specified date on


setUTCFullYears()
the basis of universal time.

It sets the hour value for the specified date on


setUTCHours()
the basis of universal time.

It sets the millisecond value for the specified


setUTCMilliseconds()
date on the basis of universal time.

It sets the minute value for the specified date on


setUTCMinutes()
the basis of universal time.

It sets the month value for the specified date on


setUTCMonth()
the basis of universal time.

It sets the second value for the specified date on


setUTCSeconds()
the basis of universal time.

toDateString() It returns the date portion of a Date object.

toISOString() It returns the date in the form ISO format string.

It returns a string representing the Date object.


toJSON() It also serializes the Date object during JSON
serialization.

toString() It returns the date in the form of string.

29
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

toTimeString() It returns the time portion of a Date object.

It converts the specified date in the form of


toUTCString()
string using UTC time zone.

valueOf() It returns the primitive value of a Date object.

DATE EXAMPLE
<html>
<body>
<script>// Create a new Date object for the current date and time
let now = new Date();
document.write("<br>Current Date and Time: " + now);

// Creating a specific Date object


let specificDate = new Date(2024, 8, 3, 14, 30, 0); // (year, month, day, hour, minute,
second)
document.write("<br>Specific Date: " + specificDate);

// Date get methods


document.write("<br>Year: " + now.getFullYear()); // Get the full year (4 digits)
document.write("<br>Month: " + (now.getMonth() + 1)); // Get the month (0-11),
add 1 to get the actual month number
document.write("<br>Date: " + now.getDate()); // Get the day of the month (1-
31)
document.write("<br>Day of Week: " + now.getDay()); // Get the day of the week
(0-6, where 0 is Sunday)
document.write("<br>Hours: " + now.getHours()); // Get the hour (0-23)
document.write("<br>Minutes: " + now.getMinutes()); // Get the minutes (0-59)
document.write("<br>Seconds: " + now.getSeconds()); // Get the seconds (0-59)
document.write("<br>Milliseconds: " + now.getMilliseconds()); // Get the milliseconds
(0-999)
document.write("<br>Time since Epoch: " + now.getTime()); // Get the time in
milliseconds since January 1, 1970

// Date set methods


now.setFullYear(2025); // Set the year to 2025
document.write("Updated Year: " + now.getFullYear());

30
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

now.setMonth(11); // Set the month to December (11 because it's 0-indexed)


document.write("<br>Updated Month: " + (now.getMonth() + 1));

now.setDate(25); // Set the day of the month to 25


document.write("<br>Updated Date: " + now.getDate());

now.setHours(10); // Set the hour to 10 AM


document.write("<br>Updated Hours: " + now.getHours());

now.setMinutes(45); // Set the minutes to 45


document.write("<br>Updated Minutes: " + now.getMinutes());

now.setSeconds(30); // Set the seconds to 30


document.write("Updated Seconds: " + now.getSeconds());

now.setMilliseconds(500); // Set the milliseconds to 500


document.write("<br>Updated Milliseconds: " + now.getMilliseconds());

// Date formatting methods


document.write("<br>ISO String: " + now.toISOString()); // Convert to ISO string
format
document.write("<br>Date String: " + now.toDateString()); // Convert to a human-
readable date string
document.write("<br>Time String: " + now.toTimeString()); // Convert to a human-
readable time string
document.write("<br>Locale String: " + now.toLocaleString()); // Convert to a locale-
specific string
document.write("<br>Locale Date String: " + now.toLocaleDateString()); // Convert to
a locale-specific date string
document.write("<br>Locale Time String: " + now.toLocaleTimeString()); // Convert to
a locale-specific time string

// Parsing dates from strings


let dateFromString = new Date("2024-09-03T14:30:00Z"); // ISO string
document.write("<br>Parsed Date from String: " + dateFromString);

let dateFromLocalString = new Date("September 3, 2024 14:30:00");


document.write("<br>Parsed Date from Local String: " + dateFromLocalString);

// Date comparisons
let earlierDate = new Date(2023, 0, 1);

31
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

let laterDate = new Date(2024, 0, 1);

document.write("<br>Is laterDate after earlierDate? " + (laterDate > earlierDate)); //


true
document.write("<br>Is laterDate before earlierDate? " + (laterDate < earlierDate)); //
false
document.write("<br>Is laterDate equal to earlierDate? " + (laterDate.getTime() ===
earlierDate.getTime())); // false
</script>
</body>
</html>

JavaScript Date Example


Let's see the simple example to print date object. It prints date and time both.

Current Date and Time: <span id="txt"></span>

<script>

var today=new Date();

document.getElementById('txt').innerHTML=today;
</script>

Let's see another code to print date/month/year.

<script>

var date=new Date();


var day=date.getDate();

var month=date.getMonth()+1;

var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);

</script>
The change in the state of an object is known as an Event. In html, there are various events
which represents that some activity is performed by the user or by the browser.
When javascript code is included in HTML, js react over these events and allow the
execution. This process of reacting over the events is called Event Handling. Thus, js
handles the HTML events via Event Handlers.

32
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

For example, when a user clicks over the browser, add js code, which will execute the task
to be performed on the event.
Some of the HTML events and their event handlers are:

Mouse events:

Event Event Handler Description


Performed

click onclick When mouse click on an element

When the cursor of the mouse comes over the


mouseover onmouseover
element

When the cursor of the mouse leaves an


mouseout onmouseout
element

When the mouse button is pressed over the


mousedown onmousedown
element

When the mouse button is released over the


mouseup onmouseup
element

mousemove onmousemove When the mouse movement takes place.

Keyboard events:

Event Event Description


Performed Handler

Keydown onkeydown When the user press and then release


& Keyup & onkeyup the key

Form events:

Event Event Description


Performed Handler

33
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

When the user focuses on an


focus onfocus
element

submit onsubmit When the user submits the form

When the focus is away from a


blur onblur
form element

When the user modifies or changes


change onchange
the value of a form element

Window/Document events

Event Event Description


Performed Handler

When the browser finishes the loading of


load onload
the page

When the visitor leaves the current


unload onunload
webpage, the browser unloads it

When the visitor resizes the window of the


resize onresize
browser

Click Event

<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write("This is JavaTpoint");
}
//-->
</script>
<form>

34
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<input type="button" onclick="clickevent()" value="Who's this?"/>


</form>
</body>
</html>
MouseOver Event

<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is JavaTpoint");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
Focus Event

<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
//-->
</script>
</body>
</html>
Keydown Event

<html>

35
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<head> Javascript Events</head>


<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
Load event
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>

Exception Handling in JavaScript


An exception signifies the presence of an abnormal condition which requires special
operable techniques. In programming terms, an exception is the anomalous code that
breaks the normal flow of the code. Such exceptions require specialized programming
constructs for its execution.
What is Exception Handling
In programming, exception handling is a process or method used for handling the
abnormal statements in the code and executing them. It also enables to handle the flow
control of the code/program. For handling the code, various handlers are used that
process the exception and execute the code. For example, the Division of a non-zero value
with zero will result into infinity always, and it is an exception. Thus, with the help of
exception handling, it can be executed and handled.

36
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

In exception handling:
A throw statement is used to raise an exception. It means when an abnormal condition
occurs, an exception is thrown using throw.
The thrown exception is handled by wrapping the code into the try…catch block. If an error
is present, the catch block will execute, else only the try block statements will get
executed.
Thus, in a programming language, there can be different types of errors which may disturb
the proper execution of the program.
Types of Errors
While coding, there can be three types of errors in the code:
1. Syntax Error: When a user makes a mistake in the pre-defined syntax of a
programming language, a syntax error may appear.
2. Runtime Error: When an error occurs during the execution of the program, such an
error is known as Runtime error. The codes which create runtime errors are known as
Exceptions. Thus, exception handlers are used for handling runtime errors.
3. Logical Error: An error which occurs when there is any logical mistake in the program
that may not produce the desired output, and may terminate abnormally. Such an
error is known as Logical error
Exception Handling Statements
There are following statements that handle if any exception occurs:
o throw statements
o try…catch statements
o try…catch…finally statements.
JavaScript try…catch
A try…catch is a commonly used statement in various programming languages. Basically,
it is used to handle the error-prone part of the code. It initially tests the code for all
possible errors it may contain, then it implements actions to tackle those errors (if occur).
A good programming approach is to keep the complex code within the try…catch
statements.

try{} statement: Here, the code which needs possible error testing is kept within the try
block. In case any error occur, it passes to the catch{} block for taking suitable actions and
handle the error. Otherwise, it executes the code written within.

catch{} statement: This block handles the error of the code by executing the set of
statements written within the block. This block contains either the user-defined exception
handler or the built-in handler. This block executes only when any error-prone code needs
to be handled in the try block. Otherwise, the catch block is skipped.

Syntax:

37
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

try{
expression; } //code to be written.
catch(error){
expression; } // code for handling the error.
try…catch example
<html>
<head> Exception Handling</br></head>
<body>
<script>
try{
var a= ["34","32","5","31","24","44","67"]; //a is an array
document.write(a); // displays elements of a
document.write(b); //b is undefined but still trying to fetch its value. Thus catch block wil
l be invoked
}catch(e){
alert("There is error which shows "+e.message); //Handling error
}
</script>
</body>
</html>
Throw Statement
Throw statements are used for throwing user-defined errors. User can define and throw
their own custom errors. When throw statement is executed, the statements present after
it will not execute. The control will directly pass to the catch block.
Syntax:
throw exception;
try…catch…throw syntax
try{
throw exception; // user can define their own exception
}
catch(error){
expression; } // code for handling exception.
The exception can be a string, number, object, or boolean value.
throw example with try…catch
<html>
<head>Exception Handling</head>
<body>
<script>
try {
throw new Error('This is the throw keyword'); //user-defined throw statement.
}

38
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

catch (e) {
document.write(e.message); // This will generate an error message
}
</script>
</body>
</html>
With the help of throw statement, users can create their own errors.
try…catch…finally statements
Finally is an optional block of statements which is executed after the execution of try and
catch statements. Finally block does not hold for the exception to be thrown. Any
exception is thrown or not, finally block code, if present, will definitely execute. It does not
care for the output too.
Syntax:
try{
expression;
}
catch(error){
expression;
}
finally{
expression; } //Executable code
try…catch…finally example
<html>
<head>Exception Handling</head>
<body>
<script>
try{
var a=2;
if(a==2)
document.write("ok");
}
catch(Error){
document.write("Error found"+e.message);
}
finally{
document.write("Value of a is 2 ");
}
</script>
</body>
</html>

39
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

JavaScript RegExp(Regular Expression)


A regular expression is a character sequence defining a search pattern. It’s employed in
text searches and replacements, describing what to search for within a text. Ranging from
single characters to complex patterns, regular expressions enable various text operations
with versatility and precision.

A regular expression can be a single character or a more complicated pattern.

In regular expressions (regex) for pattern matching, various symbols are used to define
specific search patterns. These symbols are part of a syntax that allows powerful and
flexible matching of string data. Here’s a breakdown of commonly used symbols and their
meanings:
Basic Symbols
1. ^ (Caret):
o Matches the beginning of a string.
o Example: ^Hello matches "Hello" only if it appears at the beginning of the
string.
2. $ (Dollar Sign):
o Matches the end of a string.
o Example: world$ matches "world" only if it appears at the end of the string.
3. . (Dot):
o Matches any single character except for a newline.
o Example: a.b matches "aab", "acb", etc., but not "ab".
4. * (Asterisk):
o Matches 0 or more of the preceding character.
o Example: ab*c matches "ac", "abc", "abbc", "abbbc", etc.
5. + (Plus Sign):
o Matches 1 or more of the preceding character.
o Example: ab+c matches "abc", "abbc", "abbbc", etc., but not "ac".
6. ? (Question Mark):
o Matches 0 or 1 of the preceding character (i.e., the preceding character is
optional).
o Example: colou?r matches both "color" and "colour".
7. | (Pipe):
o Acts as an OR operator.
o Example: apple|orange matches either "apple" or "orange".
Character Sets and Ranges
8. [] (Square Brackets):
o Character set: Matches any one character inside the brackets.
o Example: [abc] matches "a", "b", or "c".

40
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

9. [a-z]:
o Character range: Matches any lowercase letter from a to z.
o Example: [a-z] matches any lowercase letter (a through z).
10. [^] (Negated Character Set):
o Negation: Matches any character except those inside the brackets.
o Example: [^a-z] matches any character except lowercase letters.
Quantifiers
11. {n}:
o Matches exactly n occurrences of the preceding character.
o Example: a{3} matches "aaa" but not "aa" or "aaaa".
12. {n,}:
o Matches n or more occurrences of the preceding character.
o Example: a{2,} matches "aa", "aaa", "aaaa", etc.
13. {n,m}:
o Matches between n and m occurrences of the preceding character.
o Example: a{2,4} matches "aa", "aaa", and "aaaa", but not "a" or "aaaaa".
Special Characters and Escape Sequences
14. \ (Backslash):
o Used to escape special characters, so they can be treated as literals.
o Example: \. matches a literal dot, not any character.
o Example: \\ matches a literal backslash.
15. \d:
o Matches any digit (equivalent to [0-9]).
o Example: \d{2,4} matches 2 to 4 digits.
16. \D:
o Matches any non-digit character (equivalent to [^0-9]).
o Example: \D matches any character that is not a digit.
17. \w:
o Matches any word character (letters, digits, and underscores) (equivalent to
[a-zA-Z0-9_]).
o Example: \w+ matches "hello123" or "test_var".
18. \W:
o Matches any non-word character (equivalent to [^a-zA-Z0-9_]).
o Example: \W matches symbols like "!", "@", "#", etc.
19. \s:
o Matches any whitespace character (spaces, tabs, newlines).
o Example: \s matches a space or tab.
20. \S:
o Matches any non-whitespace character.
o Example: \S matches any character that is not a space or tab.
Grouping and Capturing

41
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

21. () (Parentheses):
o Used for grouping characters or expressions.
o Example: (abc)+ matches one or more occurrences of the string "abc".
o Capturing groups: Parentheses capture the matched text, allowing you to
reference or extract it later.
22. (?:) (Non-Capturing Group):
o Groups characters but does not capture the matched text.
o Example: (?:abc)+ matches "abcabc" but doesn't capture the "abc" portion.
Anchors
23. \b:
o Matches a word boundary (the position between a word and a space or
punctuation).
o Example: \bcat\b matches "cat" as a whole word but not "catalog" or
"scattered".
24. \B:
o Matches a non-word boundary.
o Example: \Bcat\B matches "catalog" but not "cat".
Example: Matching an Email Address
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
 ^: Start of the string.
 [a-zA-Z0-9._%+-]+: One or more characters from this set, allowing letters, digits, and
certain symbols.
 @: Must have an "@" symbol.
 [a-zA-Z0-9.-]+: One or more letters, digits, dots, or hyphens (domain name).
 \.: A literal dot.
 [a-zA-Z]{2,}: Two or more letters (TLD like .com, .org).
 $: End of the string.
Example: Matching a Phone Number (10 Digits)
^\d{10}$
 ^: Start of the string.
 \d{10}: Exactly 10 digits.
 $: End of the string.
Example: Matching a Password
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$
 ^: Start of the string.
 (?=.*\d): Must contain at least one digit.
 (?=.*[a-z]): Must contain at least one lowercase letter.
 (?=.*[A-Z]): Must contain at least one uppercase letter.
 .{8,}: Must be at least 8 characters long.
 $: End of the string.
Summary of Common Symbols:

42
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

Symbol Meaning
^ Start of the string
$ End of the string
. Any character (except newline)
* 0 or more of the previous character
+ 1 or more of the previous character
? 0 or 1 of the previous character
[] Character set or range
\d Any digit (0-9)
\D Any non-digit
\w Any word character (letters, digits, underscores)
\W Any non-word character
\s Any whitespace character
\S Any non-whitespace character
{n} Exactly n occurrences
{n,} n or more occurrences
{n,m} Between n and m occurrences
() Grouping and capturing
` `
\b Word boundary
Regular expressions are powerful for validating input by specifying precise patterns of
acceptable data.
JavaScript Form Validation
It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is must to authenticate user.
JavaScript provides facility to validate the form on the client-side so data processing will
be faster than server-side validation. Most of the web developers prefer JavaScript form
validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and
more fields.

Example of form validation for name, mobile no, email

<html>
<head>
<title>User Validation</title>

43
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<style>
legend {
display: block;
padding-left: 2px;
padding-right: 2px;
border: none;
}
</style>
<script>
function validate() {
var un=document.getElementById("un");
var uname=un.value;
var em = document.getElementById("e");
var email = em.value;
var m=document.getElementById("ph");
var mobile=m.value;
var unre=/^[a-zA-Z]+[0-9a-zA-Z._]*$/
var ere=/^[a-zA-Z]+([\._]?\w+)*@\w+([\._]?\w+)*(\.\w{2,3})+$/
var mre=/^[6-9][0-9]{9}$/;
if(unre.test(uname))
{
if(ere.test(email))
{
if(mre.test(mobile))
{
alert("Registered Successfully.");
return true;
}
else
{
alert("Invalid");
m.style.border = "red solid 3px";
m.value='';
m.placeholder="Invalid";
return false;
}
}
else {
alert("Invalid");
em.style.border = "red solid 3px";

44
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

em.value='';
em.placeholder="Invalid";
return false;
}
}
else {
alert("Invalid");
un.style.border = "red solid 3px";
un.value='';
un.placeholder="Invalid";
return false;
}
}
function err(ele)
{
ele.style.border = "red solid 3px";
ele.value='';
ele.placeholder="Invalid";
return false;
}
</script>
</head>
<body bgcolor="cyan">
<center>
<h1>Email Registration</h1>
<form>
<fieldset style="width:300px">
<legend>Registation Form</legend>
<table>
<tr>
<input type="text" id="un" placeholder="UserName" maxlength="10">
</tr>
<br><br>
<tr>
<input type="email" id="e" placeholder="Email" >
</tr>
<br><br>
<tr>
<input type="text" id="ph" placeholder="Mobile">
</tr>
<br><br>

45
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<br><br>
<tr><input type="submit" onclick="return validate()" value="Submit">
</tr>
</table>
</fieldset>
</form></div>
</center>
</body>
</html>

7. WHAT IS xml?
 Xml (eXtensible Markup Language) is a mark up language.
 XML is designed to store and transport data.
 Xml was released in late 90’s. it was created to provide an easy to use and store self
describing data.
 XML became a W3C Recommendation on February 10, 1998.
 XML is not a replacement for HTML.
 XML is designed to be self-descriptive.
 XML is designed to carry data, not to display data.
 XML tags are not predefined. You must define your own tags.
 XML is platform independent and language independent.

Why xml

Platform Independent and Language Independent: The main benefit of xml is that you can use
it to take data from a program like Microsoft SQL, convert it into XML then share that XML
with other programs and platforms. You can communicate between two platforms which are
generally very difficult.
The main thing which makes XML truly powerful is its international acceptance. Many
corporation use XML interfaces for databases, programming, office application mobile phones
and more. It is due to its platform independent feature.

Features and Advantages of XML

XML is widely used in the era of web development. It is also used to simplify data storage and
data sharing.
The main features or advantages of XML are given below.

1) XML separates data from HTML


If you need to display dynamic data in your HTML document, it will take a lot of work to edit
the HTML each time the data changes.

46
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

With XML, data can be stored in separate XML files. This way you can focus on using HTML/CSS
for display and layout, and be sure that changes in the underlying data will not require any
changes to the HTML.

With a few lines of JavaScript code, you can read an external XML file and update the data
content of your web page.
2) XML simplifies data sharing

In the real world, computer systems and databases contain data in incompatible formats.

XML data is stored in plain text format. This provides a software- and hardware-independent
way of storing data.

This makes it much easier to create data that can be shared by different applications.

3) XML simplifies data transport


One of the most time-consuming challenges for developers is to exchange data between
incompatible systems over the Internet.
Exchanging data as XML greatly reduces this complexity, since the data can be read by different
incompatible applications.

4) XML simplifies Platform change


Upgrading to new systems (hardware or software platforms), is always time consuming. Large
amounts of data must be converted and incompatible data is often lost.
XML data is stored in text format. This makes it easier to expand or upgrade to new operating
systems, new applications, or new browsers, without losing data.

5) XML increases data availability


Different applications can access your data, not only in HTML pages, but also from XML data
sources.

With XML, your data can be available to all kinds of "reading machines" (Handheld computers,
voice machines, news feeds, etc), and make it more available for blind people, or people with
other disabilities.

XML Example

XML documents create a hierarchical structure looks like a tree so it is known as XML Tree that
starts at "the root" and branches to "the leaves".

Example of XML Document

XML documents uses a self-describing and simple syntax:

47
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<?xml version="1.0" encoding="ISO-8859-1"?>

<note>

<to>Tove</to>

<from>Jani</from>

<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>

</note>

The first line is the XML declaration. It defines the XML version (1.0) and the encoding used
(ISO-8859-1 = Latin-1/West European character set).
The next line describes the root element of the document (like saying: "this document is a
note"):

<note>

The next 4 lines describe 4 child elements of the root (to, from, heading, and body).
<to>Tove</to>

<from>Jani</from>

<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>

And finally the last line defines the end of the root element.
</note>

XML documents must contain a root element. This element is "the parent" of all other
elements.

The elements in an XML document form a document tree. The tree starts at the root
and branches to the lowest level of the tree.
All elements can have sub elements (child elements).

<root>

<child>
<subchild>.....</subchild>

</child>

48
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

</root>

The terms parent, child, and sibling are used to describe the relationships between
elements. Parent elements have children. Children on the same level are called siblings
(brothers or sisters).

Another Example of XML: Books

File: books.xml

<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>

<author>Giada De Laurentiis</author>
<year>2005</year>

<price>30.00</price>

</book>

<book category="CHILDREN">
<title lang="en">Harry Potter</title>

<author>J K. Rowling</author>

<year>2005</year>
<price>29.99</price>

</book>
<book category="WEB">

<title lang="en">Learning XML</title>


<author>Erik T. Ray</author>
<year>2003</year>

<price>39.95</price>
</book>

</bookstore>

49
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

The root element in the example is <bookstore>. All elements in the document are contained
within <bookstore>.
The <book> element has 4 children: <title>,< author>, <year> and <price>.

Another Example of XML: Emails

File: emails.xml

<?xml version="1.0" encoding="UTF-8"?>

<emails>
<email>

<to>Vimal</to>

<from>Sonoo</from>
<heading>Hello</heading>

<body>Hello brother, how are you!</body>


</email>

<email>
<to>Peter</to>

<from>Jack</from>
<heading>Birth day wish</heading>

<body>Happy birth day Tom!</body>

</email>
<email>

<to>James</to>
<from>Jaclin</from>

<heading>Morning walk</heading>
<body>Please start morning walk to stay fit!</body>

</email>

<email>

<to>Kartik</to>

<from>Kumar</from>

50
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<heading>Health Tips</heading>

<body>Smoking is injurious to health!</body>

</email>

</emails>

XML Related Technologies

Here we have pointed out XML related technologies. There are following XML related
technologies:

No. Technology Meaning Description

1) XHTML Extensible html It is a clearer and stricter version of XML.


It belongs to the family of XML markup
languages. It was developed to make
html more extensible and increase inter-
operability with other data.

2) XML DOM XML document It is a standard document model that is


object model used to access and manipulate XML. It
defines the XML file in tree structure.

3) XSL Extensible style


it contain three sheet language i) It transforms XML into other formats,
parts: like html.
i) XSLT (xsl ii) It is used for formatting XML to screen,
transform) paper etc.
ii) XSL iii) It is a language to navigate XML
iii)XPath documents.

4) XQuery XML query It is a XML based language which is used


language to query XML based data.

5) DTD Document type It is an standard which is used to define


definition the legal elements in an XML document.

6) XSD XML schema It is an XML based alternative to dtd. It is


definition used to describe the structure of an XML
document.
XML Attributes

51
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

XML elements can have attributes. By the use of attributes we can add the information about
the element.
XML attributes enhance the properties of the elements.

Let us take an example of a book publisher. Here, book is the element and publisher is the
attribute.

<book publisher="Tata McGraw Hill"></book>

Difference between attribute and sub-element


In the context of documents, attributes are part of markup, while sub elements are part of the
basic document contents.

In the context of data representation, the difference is unclear and may be confusing.

Same information can be represented in two ways:

1st way:
<book publisher="Tata McGraw Hill"> </book>
2nd way:

<book>
<publisher> Tata McGraw Hill </publisher>

</book>

In the first example publisher is used as an attribute and in the second example
publisher is an element.

Both examples provide the same information but it is good practice to avoid attribute
in XML and use elements instead of attributes.

XML Tree Structure


An XML document has a self descriptive structure. It forms a tree structure which is referred
as an XML tree. The tree structure makes easy to describe an XML document.
A tree structure contains root element (as parent), child element and so on. It is very easy to
traverse all succeeding branches and sub-branches and leaf nodes starting from the root.

Example of an XML document

<?xml version="1.0"?>

<college>

52
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<student>

<firstname>Tamanna</firstname>

<lastname>Bhatia</lastname>

<contact>09990449935</contact>

<email>[email protected]</email>
<address>

<city>Ghaziabad</city>
<state>Uttar Pradesh</state>

<pin>201007</pin>

</address>

</student>
</college>
Let's see the tree-structure representation of the above example.

In the above example, first line is the XML declaration. It defines the XML version 1.0. Next
line shows the root element (college) of the document. Inside that there is one more element
(student). Student element contains five branches named <firstname>, <lastname>,
<contact>, <Email> and <address>.

XML Naming Rules

53
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

XML elements must follow these naming rules:

 Element names are case-sensitive

 Element names must start with a letter or underscore

 Element names cannot start with the letters xml (or XML, or Xml, etc)

 Element names can contain letters, digits, hyphens, underscores, and periods
 Element names cannot contain spaces

Any name can be used, no words are reserved (except xml).


Naming Conventions

Some commonly used naming conventions for XML elements:

Style Example Description

Lower <firstname> All letters lower case


case

Upper <FIRSTNAME> All letters upper case


case

Snake <first_name> Underscore separates words (commonly used in SQL


case databases)

Pascal <FirstName> Uppercase first letter in each word (commonly used by C


case programmers)

Camel <firstName> Uppercase first letter in each word except the first
case (commonly used in JavaScript)

XML Validation
A well formed XML document can be validated against DTD or Schema.

A well-formed XML document is an XML document with correct syntax. It is very necessary to
know about valid XML document before knowing XML validation.

Valid XML document

54
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

It must be well formed (satisfy all the basic syntax condition)

It should be behave according to predefined DTD or XML schema

Rules for well formed XML

o It must begin with the XML declaration.

o It must have one unique root element.


o All start tags of XML documents must match end tags.

o XML tags are case sensitive.


o All elements must be closed.

o All elements must be properly nested.

o All attributes values must be quoted.

o XML entities must be used for special characters.


XML DTD
What is DTD

DTD stands for Document Type Definition. It defines the legal building blocks of an XML
document. It is used to define document structure with a list of legal elements and
attributes.

Purpose of DTD
Its main purpose is to define the structure of an XML document. It contains a list of legal
elements and define the structure with the help of them.
Checking Validation
Before proceeding with XML DTD, you must check the validation. An XML document is
called "well-formed" if it contains the correct syntax.
A well-formed and valid XML document is one which have been validated against DTD.

Let's take an example of well-formed and valid XML document. It follows all the rules of
DTD.

employee.xml

<?xml version="1.0"?>
<!DOCTYPE employee SYSTEM "employee.dtd">

<employee>

55
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<firstname>vimal</firstname>

<lastname>jaiswal</lastname>

<email>[email protected]</email>

</employee>

In the above example, the DOCTYPE declaration refers to an external DTD file. The content
of the file is shown in below paragraph.

employee.dtd
<!ELEMENT employee (firstname,lastname,email)>

<!ELEMENT firstname (#PCDATA)>

<!ELEMENT lastname (#PCDATA)>


<!ELEMENT email (#PCDATA)>

Description of DTD
<!DOCTYPE employee : It defines that the root element of the document is employee.

<!ELEMENT employee: It defines that the employee element contains 3 elements


"firstname, lastname and email".

<!ELEMENT firstname: It defines that the firstname element is #PCDATA typed. (parse-
able data type).
<!ELEMENT lastname: It defines that the lastname element is #PCDATA typed. (parse-able
data type).

<!ELEMENT email: It defines that the email element is #PCDATA typed. (parse-able data
type).

XML DTD with entity declaration


A doctype declaration can also define special strings that can be used in the XML file.

An entity has three parts:

1. An ampersand (&)

2. An entity name
3. A semicolon (;)

Syntax to declare entity:

56
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<!ENTITY entity-name "entity-value">

Let's see a code to define the ENTITY in doctype declaration.

author.xml

<?xml version="1.0" standalone="yes" ?>

<!DOCTYPE author [
<!ELEMENT author (#PCDATA)>

<!ENTITY sj "Sonoo Jaiswal">


]>

<author>&sj;</author>

XML Schema

An XML Schema describes the structure of an XML document, just like a DTD.
An XML document with correct syntax is called "Well Formed".
An XML document validated against an XML Schema is both "Well Formed" and "Valid".

XML Schema is an XML-based alternative to DTD:

<xs:element name="note">

<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

The Schema above is interpreted like this:

 <xs:element name="note"> defines the element called "note"


 <xs:complexType> the "note" element is a complex type

 <xs:sequence> the complex type is a sequence of elements

57
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

 <xs:element name="to" type="xs:string"> the element "to" is of type string (text)

 <xs:element name="from" type="xs:string"> the element "from" is of type string

 <xs:element name="heading" type="xs:string"> the element "heading" is of type


string

 <xs:element name="body" type="xs:string"> the element "body" is of type string

XML Schemas are More Powerful than DTD

 XML Schemas are written in XML


 XML Schemas are extensible to additions

 XML Schemas support data types

 XML Schemas support namespaces


Why Use an XML Schema?

With XML Schema, your XML files can carry a description of its own format.
With XML Schema, independent groups of people can agree on a standard for
interchanging data.
With XML Schema, you can verify data.

XML Schemas Support Data Types

One of the greatest strengths of XML Schemas is the support for data types:
 It is easier to describe document content

 It is easier to define restrictions on data


 It is easier to validate the correctness of data

 It is easier to convert data between different data types


XML Schemas use XML Syntax
Another great strength about XML Schemas is that they are written in XML:

 You don't have to learn a new language


 You can use your XML editor to edit your Schema files

 You can use your XML parser to parse your Schema files
 You can manipulate your Schemas with the XML DOM

 You can transform your Schemas with XSLT

58
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

Displaying XML with XSLT


XSLT (eXtensible Stylesheet Language Transformations) is the recommended
style sheet language for XML.

XSLT is far more sophisticated than CSS. With XSLT you can add/remove
elements and attributes to or from the output file. You can also rearrange
and sort elements, perform tests and make decisions about which elements
to hide and display, and a lot more.

XSLT uses XPath to find information in an XML document.

XSLT Example

We will use the following XML document:

<?xml version="1.0" encoding="UTF-8"?>


<breakfast_menu>

<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waffles with plenty of real
maple syrup</description>
<calories>650</calories>
</food>

<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>Light Belgian waffles covered with strawberries and
whipped cream</description>
<calories>900</calories>
</food>

<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>Light Belgian waffles covered with an assortment of fresh
berries and whipped cream</description>
<calories>900</calories>
</food>

<food>

59
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

<name>French Toast</name>
<price>$4.50</price>
<description>Thick slices made from our homemade sourdough
bread</description>
<calories>600</calories>
</food>

<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>Two eggs, bacon or sausage, toast, and our ever-popular
hash browns</description>
<calories>950</calories>
</food>

</breakfast_menu>

Use XSLT to transform XML into HTML, before it is displayed in a browser:

Example XSLT Stylesheet:


<?xml version="1.0" encoding="UTF-8"?>
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform
">
<body style="font-family:Arial;font-size:12pt;background-
color:#EEEEEE">
<xsl:for-each select="breakfast_menu/food">
<div style="background-color:teal;color:white;padding:4px">
<span style="font-weight:bold"><xsl:value-
of select="name"/> - </span>
<xsl:value-of select="price"/>
</div>
<div style="margin-left:20px;margin-bottom:1em;font-size:10pt">
<p>
<xsl:value-of select="description"/>
<span style="font-style:italic"> (<xsl:value-
of select="calories"/> calories per serving)</span>
</p>
</div>
</xsl:for-each>
</body>
</html>

60
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

XML DOM and SAX Parsers are two common methods for parsing XML
documents. They serve the same purpose (to parse XML) but do so in fundamentally
different ways. Here’s a comparison to explain both:

1. XML DOM (Document Object Model) Parser


What is DOM?

 The DOM (Document Object Model) is an API for XML (and HTML) documents. It
represents the entire XML document as a tree structure in memory, where each node
is an object representing a part of the document (like elements, attributes, text, etc.).

Key Features of DOM:

 Tree-based parsing: The entire XML document is loaded into memory and represented
as a hierarchical tree structure.
 Random access: You can traverse the tree in any direction, meaning you can access
and manipulate any part of the document at any time.

 Full document available in memory: The entire document is read and stored in
memory before any operations are performed.

 Memory-intensive: Since the entire XML file is loaded into memory, DOM parsing is
not ideal for very large XML files.

Use Case:

 Ideal when the entire XML document needs to be accessed and modified, or when
random access to various parts of the document is necessary.
Example of DOM Parsing:

In Java, the DOM parser reads the entire XML into memory, after which you can traverse it.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("file.xml"));

// Accessing the root element


Element root = document.getDocumentElement();
System.out.println("Root element: " + root.getNodeName());
Pros of DOM:

 Easy to use: Since the whole document is available in memory, it’s easier to navigate
and modify.

61
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

 Rich API: Provides a wide range of methods to manipulate the document.

Cons of DOM:

 Memory consumption: The entire document must be loaded into memory, which is
inefficient for large XML files.

 Slower performance: Parsing large files may slow down performance due to high
memory usage.

2. SAX (Simple API for XML) Parser


What is SAX?
 SAX (Simple API for XML) is a stream-based parser. Unlike DOM, it doesn’t load the
entire XML document into memory. Instead, it reads the XML document sequentially
and triggers events (such as start element, end element, etc.) when it encounters
specific XML structures.

Key Features of SAX:


 Event-driven parsing: SAX parses the document by reading it sequentially and fires
events as it encounters XML elements.

 No random access: SAX doesn’t store the document in memory, so you can’t navigate
back and forth.

 Low memory usage: Since SAX processes the document piece by piece, it is memory-
efficient and suitable for parsing very large XML files.
 Read-only parsing: SAX is better suited for reading data rather than modifying or
manipulating it.

Use Case:
 Ideal when you need to read or process large XML files and memory efficiency is
important, but you don’t need to modify the document or access random parts of it.
Example of SAX Parsing:

In Java, the SAX parser triggers events as it reads the XML, allowing you to handle the data
during parsing.

SAXParserFactory factory = SAXParserFactory.newInstance();


SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
public void startElement(String uri, String localName, String qName, Attributes attributes) {
System.out.println("Start Element: " + qName);
}

62
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

public void endElement(String uri, String localName, String qName) {


System.out.println("End Element: " + qName);
}

public void characters(char ch[], int start, int length) {


System.out.println("Characters: " + new String(ch, start, length));
}
};

saxParser.parse(new File("file.xml"), handler);


Pros of SAX:

 Memory efficient: Only processes one part of the document at a time, making it ideal
for large XML files.

 Faster for large files: Since it doesn’t load the whole document into memory, it can be
faster for large files.

Cons of SAX:

 Complex to use: Since it’s event-driven, the developer must handle events manually,
which can be more difficult to manage.
 No random access: You can’t move back and forth in the document or modify it once
parsed.

Comparison: DOM vs. SAX

Feature DOM Parser SAX Parser

Tree-based (loads entire document into Event-driven (sequential, no


Parsing type
memory) memory storage)

Memory
High (entire document in memory) Low (processes one piece at a time)
usage

Random access (can access any part of


Access type Sequential (no random access)
the document)

Modification Easy to modify document Not suitable for modification

Performance Slower for large files Faster for large files

63
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25

Feature DOM Parser SAX Parser

More complex due to event-based


Ease of use Easier to navigate and manipulate
handling

When to Use:

 DOM: Use DOM when you need to access and possibly modify different parts of the
XML document at various times and when the document size is relatively small.

 SAX: Use SAX when the XML document is large and you only need to read data from it
in a memory-efficient way without needing to store or modify the entire document.

64

You might also like