Unit II
Unit II
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
The example below "finds" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":
In this example JavaScript changes the value of the src (source) attribute of
an <img> tag:
document.getElementById("demo").style.fontSize = "35px";
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>
<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>
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.
<!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
Automatically
Using var
Using let
Using const
Note
The var keyword was used in all JavaScript code from 1995 to 2015.
3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you can't use const
Strings are written inside double or single quotes. Numbers are written without quotes.
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!';
Arithmetic Operators
Assignment Operators
Comparison Operators
String Operators
Logical Operators
Bitwise Operators
Ternary Operators
Type Operators
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>
</head>
<body>
<script>
// Declare variables
let a = 10;
let b = 3;
// Arithmetic operations
</script>
</body>
</html>
6
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
Assignment
let x = 10;
x += 5;
EXAMPLE
<!DOCTYPE html>
<html lang="en">
<body>
<script>
// Declare variables
let x = 10;
let y = 5;
// Basic assignment
let z = x; // z = 10
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
7
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
</script>
</body>
</html>
Operator Description
== equal to
!= not equal
? 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>
<script>
// Declare variables
let a = 10;
let b = 20;
// Comparison operators
let equal = (a == b); // Equal to
let strictlyEqual = (a === b); // Strictly equal to (checks both value and type)
</script>
</body>
</html>
9
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
Operator Description
|| logical or
! logical not
EXAMPLE
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h2>Logical Operators Example</h2>
<script>
// Declare variables
let a = true;
let b = false;
// Logical operators
10
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
</script>
</body>
</html>
Operator Description
|| logical or
! logical not
EXAMPLE
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Logical Operators</title>
</head>
<body>
<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 (||)
</script>
</body>
</html>
CONTROL STATEMENTS
<head>
</head>
<body>
12
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
} 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">
<body>
<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:
</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>
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>
<script>
let i = 1;
</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>
<script>
let j = 1;
<html lang="en">
<head>
</head>
<body>
if (i === 3) {
break;
}
16
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
document.write("<br>");
if (i === 3) {
continue;
}
</script>
</body>
</html>
JAVASCRIPT FUNCTIONS
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, ...)
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">
<body>
<script>
// Defining a simple function
function greet(name) {
</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
18
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
1. object={property1:value1,property2:value2.....propertyN:valueN}
As you can see, property and value is separated by : (colon).
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
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.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
</script>
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
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>
<script>
var i;
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
document.write(emp[i] + "<br>");
</script>
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 copies the part of the given array with its own elements
copywithin()
and returns the modified array.
22
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
23
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>
<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
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>
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
Date()
Date(milliseconds)
Date(dateString)
Methods Description
27
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
28
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
29
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
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);
30
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
// 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
<script>
document.getElementById('txt').innerHTML=today;
</script>
<script>
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:
Keyboard events:
Form events:
33
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
Window/Document events
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
<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
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
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.
<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.
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.
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.
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".
47
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
<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).
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">
<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>.
File: emails.xml
<emails>
<email>
<to>Vimal</to>
<from>Sonoo</from>
<heading>Hello</heading>
<email>
<to>Peter</to>
<from>Jack</from>
<heading>Birth day wish</heading>
</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>
</email>
</emails>
Here we have pointed out XML related technologies. There are following XML related
technologies:
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.
In the context of data representation, the difference is unclear and may be confusing.
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 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>.
53
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
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
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.
54
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
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)>
Description of DTD
<!DOCTYPE employee : It defines that the root element of the document is employee.
<!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).
1. An ampersand (&)
2. An entity name
3. A semicolon (;)
56
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
author.xml
<!DOCTYPE author [
<!ELEMENT author (#PCDATA)>
<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".
<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>
57
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
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.
One of the greatest strengths of XML Schemas is the support for data types:
It is easier to describe document content
You can use your XML parser to parse your Schema files
You can manipulate your Schemas with the XML DOM
58
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
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 Example
<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>
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:
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.).
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"));
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
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.
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.
62
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
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.
Memory
High (entire document in memory) Low (processes one piece at a time)
usage
63
VARDHAMAN COLLGE OF ENGINEERING
Department of Information Technology
III B. TECH I SEM WEB TECHNOLOGIES
A.Y 2024-25
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