0% found this document useful (0 votes)
33 views112 pages

Web Programming Unit-2

This document provides an overview of JavaScript, a lightweight, object-based scripting language primarily used for client-side web development. It covers various aspects including control statements, functions, the DOM model, built-in objects, and error handling, as well as practical examples of using JavaScript in HTML. Additionally, it discusses event handling and the use of built-in JavaScript objects for various functionalities.

Uploaded by

rameshkumar.m
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)
33 views112 pages

Web Programming Unit-2

This document provides an overview of JavaScript, a lightweight, object-based scripting language primarily used for client-side web development. It covers various aspects including control statements, functions, the DOM model, built-in objects, and error handling, as well as practical examples of using JavaScript in HTML. Additionally, it discusses event handling and the use of built-in JavaScript objects for various functionalities.

Uploaded by

rameshkumar.m
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/ 112

UNIT 2

CLIENT SIDE SCRIPTING LANGUAGES

Introduction to JavaScript–Control statements -


Function - JavaScript DOM Model-Date and Objects–
Regular Expressions- Exception Handling Built-in
Objects.
JAVA SCRIPT
Introduction
• JavaScript is a object-based scripting language and
it is light weighted.
• It is first implemented by Netscape (with help from
Sun Microsystems).
• JavaScript was created by Brendan Eich at
Netscape in 1995 for the purpose of allowing code
in web-pages (performing logical operation on
client side).
• It is not compiled but translated. JavaScript
Translator is responsible to translate the JavaScript
code which is embedded in browser.
Where it is used?

• It is used to create interactive websites. It is


mainly used for:
• Client-side validation
• Dynamic drop-down menus
• Displaying date and time
• Build small but complete client side programs .
• Displaying popup windows and dialog boxes (like
alert dialog box, confirm dialog box and prompt
dialog box)
• Displaying clocks etc.
Features of JavaScript
JavaScript is a client side technology, it is mainly used for gives client side
validation, but it have lot of features which are given below;
Way of Using JavaScript

• There are three places to put the JavaScript


code.
• Between the <body> </body> tag of html
(Inline JavaScript)
• Between the <head> </head> tag of html
(Internal JavaScript)
• In .js file (External JavaScript)
How to Put a JavaScript Into an HTML
Page?
<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
• Inline JavaScript
• When java script was written within the html
element using attributes related to events of
the element then it is called as inline java
script.
• Example of Inline JavaScript
• Example How to use JavaScript
• <html> <form> <input type="button"
value="Click" onclick="alert('Button
Clicked')"/> </form> </html>
• Output:
Click
Internal JavaScript
• When java script was written within the section using element
then it is called as internal java script.
• Example of Internal JavaScript
• <html>
• <head>
• <script>
• function msg()
• { alert("Welcome in JavaScript"); }
• </script>
• </head>
• <form>
• <input type="button" value="Click" onclick="msg()"/>
• </form>
• </html>
• Output: click
External JavaScript
• Writing java script in a separate file with extension
.js is called as external java script. For adding the
reference of an external java script file to your html
page, use tag with src attribute as follows
• Example
• <script type="text/javascript" src="filename.js"/>
• Create a file with name functions.js and write the
following java script functions in it.
• message.js
• Example
• function msg() { alert("Welcome in JavaScript"); }
• Example
• <html>
• <head>
• <script type="text/javascript" src="message.js">
• </script>
• </head>
• <body>
• <form>
• <input type="button" value="click" onclick="msg()"/>
• </form>
• </body>
• </html>
• output: click
alert(), confirm(), and prompt()
<script type="text/javascript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt("How old are you?","20");
</script>
alert() and confirm()
alert("Text to be displayed");

• Display a message in a dialog box.


• The dialog box will block the browser.

var answer = confirm("Are you sure?");

▪ Display a message in a dialog box with two buttons: "OK" or


"Cancel".
▪ confirm() returns true if the user click "OK". Otherwise it
returns false.
prompt()
prompt("What is your student id number?");
prompt("What is your name?”, "No name");

• Display a message and allow the user to enter a value


• The second argument is the "default value" to be displayed in
the input textfield.
• Without the default value, "undefined" is shown in the input
textfield.

• If the user click the "OK" button, prompt() returns the


value in the input textfield as a string.
• If the user click the "Cancel" button, prompt() returns null.
Identifier
• Same as Java/C++ except that it allows an
additional character – '$'.

• Contains only 'A' – 'Z', 'a' – 'z', '0' – '9', '_', '$'
• First character cannot be a digit
• Case-sensitive
• Cannot be reserved words or keywords
Variable and Variable Declaration
<head><script type="text/javascript">
// We are in the default scope – the "window" object.
x = 3; // same as "window.x = 3"
var y = 4; // same as "y = 4" or "window.y = 4"

{ // Introduce a block to creat a local scope


x = 0; // Same as "window.x = 0"
var y = 1; // This is a local variable y
}

alert("x=" + x + ", y=" + y); // Print x=0, y=4

</script></head>

• Local variable is declared using the keyword 'var'.


• Dynamic binding – a variable can hold any type of value
• If a variable is used without being declared, the variable is created
automatically.
– If you misspell a variable name, program will still run (but works incorrectly)
• Primitive data types
Data Types
– Number: integer & floating-point numbers
– Boolean: true or false
– String: a sequence of alphanumeric characters

• Composite data types (or Complex data types)


– Object: a named collection of data
– Array: a sequence of values (an array is actually a predefined object)

• Special data types


– Null: the only value is "null" – to represent nothing.
– Undefined: the only value is "undefined" – to represent the value of an
unintialized variable
Operators
• Arithmetic operators
– +, -, *, /, %

• Post/pre increment/decrement
– ++, --

• Comparison operators
– ==, !=, >, >=, <, <=
– ===, !== (Strictly equals and strictly not equals)
• i.e., Type and value of operand must match / must not
match
== vs ===
// Type conversion is performed before comparison
var v1 = ("5" == 5); // true

// No implicit type conversion.


// True if only if both types and values are equal
var v2 = ("5" === 5); // false

var v3 = (5 === 5.0); // true

var v4 = (true == 1); // true (true is converted to 1)

var v5 = (true == 2); // false (true is converted to 1)

var v6 = (true == "1") // true


Logical Operators
• ! – Logical NOT
• && – Logical AND
– OP1 && OP2
– If OP1 is true, expression evaluates to the value of OP2.
Otherwise the expression evaluates to the value of OP1.
– Results may not be a boolean value.

• || – Logical OR
– OP1 || OP2
– If OP1 is true, expression evaluates to the value of OP1.
Otherwise the expression evaluates to the value of OP2.
var tmp1 = null && 1000; // tmp1 is null

var tmp2 = 1000 && 500; // tmp2 is 500

var tmp3 = false || 500; // tmp3 is 500

var tmp4 = "" || null; // tmp4 is null

var tmp5 = 1000 || false; // tmp5 is 1000

// If foo is null, undefined, false, zero, NaN,


// or an empty string, then set foo to 100.
foo = foo || 100;
Operators (continue)
• String concatenation operator
–+
– If one of the operand is a string, the other operand is
automatically converted to its equivalent string value.

• Assignment operators
– =, +=, -=, *=, /=, %=

• Bitwise operators
– &, |, ^, >>, <<, >>>
Conditional Statements
• “if” statement
• “if … else” statement
• "? :" ternary conditional statement
• “switch” statement

• The syntax of these statements are similar to


those found in C and Java.
Conditional Statements

In JavaScript we have the following conditional statements:


• if statement - use this statement if you want to execute
some code only if a specified condition is true
• if...else statement - use this statement if you want to
execute some code if the condition is true and another
code if the condition is false
• if...else if....else statement - use this statement if you
want to select one of many blocks of code to be executed
• switch statement - use this statement if you want to
select one of many blocks of code to be executed
Conditional Statements - 2
if (condition)
{
code to be executed if condition is true
}

if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Conditional Statements Examples
<script>
x=3
if(x<0)
{
alert (“negatif”)
}
else
{
alert (“pozitif”)
}
</script>
Conditional Statements Examples - 2
<script>
c=confirm(“Kitap Okuyor musunuz?”)
if(c)
{
alert (“tebrikler walla”)
}
else
{
alert (“ayıp ettiniz ama”)
}
</script>
Conditional Statements Examples - 3
<script>
p=prompt("Ankara'nın plaka numarası nedir?", " ")
if(p=="06")
{
alert("Doğru")
}
else
{
alert("Yanlış")
}
</script>
Built-In Functions
• eval(expr)
– evaluates an expression or statement
• eval("3 + 4"); // Returns 7 (Number)
• eval("alert('Hello')"); // Calls the function alert('Hello')

• isFinite(x)
– Determines if a number is finite

• isNaN(x)
– Determines whether a value is “Not a Number”
Built-In Functions
• parseInt(s)
• parseInt(s, radix)
– Converts string literals to integers
– Parses up to any character that is not part of a valid integer
• parseInt("3 chances") // returns 3
• parseInt(" 5 alive") // returns 5
• parseInt("How are you") // returns NaN
• parseInt("17", 8) // returns 15

• parseFloat(s)
– Finds a floating-point value at the beginning of a string.
• parseFloat("3e-1 xyz") // returns 0.3
• parseFloat("13.5 abc") // returns 13.5
Events
• An event occurs as a result of some activity
– e.g.:
• A user clicks on a link in a page
• Page finished loaded
• Mouse cursor enter an area
• A preset amount of time elapses
• A form is being submitted
Event Handlers
• Event Handler – a segment of codes (usually a
function) to be executed when an event
occurs

• We can specify event handlers as attributes in


the HTML tags.

• The attribute names typically take the form


"onXXX" where XXX is the event name.
– e.g.:
<a href="…" onClick="alert('Bye')">Other
Website</a>
Event Handlers
Event Handlers Triggered when
onChange The value of the text field, textarea, or a drop down list
is modified
onClick A link, an image or a form element is clicked once
onDblClick The element is double-clicked
onMouseDown The user presses the mouse button
onLoad A document or an image is loaded
onSubmit A user submits a form
onReset The form is reset
onUnLoad The user closes a document or a frame
onResize A form is resized by the user

For a complete list, see http://www.w3schools.com/htmldom/dom_obj_event.asp


onClick Event Handler Example
<html>
<head>
<title>onClick Event Handler Example</title>
<script type="text/javascript">
function warnUser() {
return confirm("Are you a student?”);
}
</script>
</head>
<body>
<a href="ref.html" onClick="return warnUser()">
<!--
If onClick event handler returns false, the link
is not followed.
-->
Students access only</a>
</body>
</html>
onLoad Event Handler Example
<html><head>
<title>onLoad and onUnload Event Handler Example</title>
</head>
<body
onLoad="alert('Welcome to this page')"
onUnload="alert('Thanks for visiting this page')"
>
Load and UnLoad event test.
</body>
</html>
onMouseOver & onMouseOut Event Handler
<html>
<head>
<title>onMouseOver / onMouseOut Event Handler Demo</title>
</head>
<body>
<a href="http://www.cuhk.edu.hk"
onMouseOver="window.status='CUHK Home'; return true;"
onMouseOut="status=''"
>CUHK</a>
</body>
</html>

• When the mouse cursor is over the link, the browser displays the text "CUHK
Home" instead of the URL.
• The "return true;" of onMouseOver forces browser not to display the URL.
• window.status and window.defaultStatus are disabled in Firefox.
onSubmit Event Handler Example
<html><head>
<title>onSubmit Event Handler Example</title>
<script type="text/javascript">
function validate() {
// If everything is ok, return true
// Otherwise return false
}
</script>
</head>
<body>
<form action="MessageBoard" method="POST"
onSubmit="return validate();"
>

</form></body></html>

• If onSubmit event handler returns false, data is not submitted.


• If onReset event handler returns false, form is not reset
Build-In JavaScript Objects
Object Description
Array Creates new array objects
Boolean Creates new Boolean objects
Date Retrieves and manipulates dates and times
Error Returns run-time error information
Function Creates new function objects
Math Contains methods and properties for performing mathematical
calculations
Number Contains methods and properties for manipulating numbers.
String Contains methods and properties for manipulating text strings

• See online references for complete list of available methods in these objects:
http://javascript-reference.info/
String Object (Some useful methods)
• length
–A string property that tells the number of character in the string
• charAt(idx)
–Returns the character at location "idx"
• toUpperCase(), toLowerCase()
–Returns the same string with all uppercase/lowercase letters
• substring(beginIdx)
–Returns a substring started at location "beginIdx"
• substring(beginIdx, endIdx)
–Returns a substring started at "beginIdx" until "endIdx" (but
not including "endIdx"
• indexOf(str)
–Returns the position where "str" first occurs in the string
Error and Exception Handling in JavaScript
• Javascript makes no distinction between Error
and Exception (Unlike Java)
• Handling Exceptions
– The onError event handler
• A method associated with the window object.
• It is called whenever an exception occurs
– The try … catch … finally block
• Similar to Java try … catch … finally block
• For handling exceptions in a code segment
– Use throw statement to throw an exception
• You can throw value of any type
– The Error object
• Default object for representing an exception
• Each Error object has a name and message properties
How to use “onError” event handler?
<html>
<head>
<title>onerror event handler example</title>
<script type="text/javascript">
function errorHandler(){
alert("Error Ourred!");
}
// JavaScript is casesensitive
// Don't write onerror!
window.onError = errorHandler;
</script>
</head>
<body>
<script type="text/javascript">
document.write("Hello there;
</script>
</body>
</html>
try … catch … finally
try {
// Contains normal codes that might throw an exception.

// If an exception is thrown, immediately go to


// catch block.

} catch ( errorVariable ) {
// Codes here get executed if an exception is thrown
// in the try block.

// The errorVariable is an Error object.

} finally {
// Executed after the catch or try block finish

// Codes in finally block are always executed


}
// One or both of catch and finally blocks must accompany the try
block.
try … catch … finally example
<script type="text/javascript">
try{
document.write("Try block begins<br>");
// create a syntax error
eval ("10 + * 5");

} catch( errVar ) {
document.write("Exception caught<br>");
// errVar is an Error object
// All Error objects have a name and message properties
document.write("Error name: " + errVar.name + "<br>");
document.write("Error message: " + errVar.message +
"<br>");
} finally {
document.write("Finally block reached!");
}
</script>
Throwing Exception
<script type="text/javascript">
try{
var num = prompt("Enter a number (1-2):", "1");
// You can throw exception of any type
if (num == "1")
throw "Some Error Message";
else
if (num == "2")
throw 123;
else
throw new Error ("Invalid input");
} catch( err ) {
alert(typeof(errMsg) + "\n" + err);
// instanceof operator checks if err is an Error object
if (err instanceof Error)
alert("Error Message: " + err.message);
}
</script>
Document Object Model (DOM)
• When a web page is loaded, the browser
creates a Document Object Model of the page.
• Representation of the current web page as a
tree of Javascript objects
• allows you to view/modify page elements in
script code after page has loaded
• client side = highly responsive interactions
• browser-independent
• allows progressive enhancement.
• With the object model, JavaScript gets all the power it
needs to create dynamic HTML:
• JavaScript can change all the HTML elements in the
page
• JavaScript can change all the HTML attributes in the
page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and
attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the
page
• JavaScript can create new HTML events in the page
What is the DOM?

• The DOM is a W3C (World Wide Web Consortium)


standard.
• The DOM defines a standard for accessing documents:
• "The W3C Document Object Model (DOM) is a platform
and language-neutral interface that allows programs and
scripts to dynamically access and update the content,
structure, and style of a document."
• The W3C DOM standard is separated into 3 different
parts:
• Core DOM - standard model for all document types
• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents
What is the HTML DOM?

• The HTML DOM is a standard object model


and programming interface for HTML. It
defines:
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements
JavaScript - HTML DOM Methods

• HTML DOM methods are actions you can


perform (on HTML Elements).
• HTML DOM properties are values (of HTML
Elements) that you can set or change.
The DOM Programming Interface

• The HTML DOM can be accessed with JavaScript


(and with other programming languages).
• In the DOM, all HTML elements are defined
as objects.
• The programming interface is the properties and
methods of each object.
• A property is a value that you can get or set (like
changing the content of an HTML element).
• A method is an action you can do (like add or
deleting an HTML element).
Example
• The following example changes the content (the
innerHTML) of the <p> element with id="demo":
• <html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML
= "Hello World!";
</script>
</body>
</html>
The getElementById Method
• The most common way to access an HTML
element is to use the id of the element.
• In the example above the getElementById method
used id="demo" to find the element.
The innerHTML Property
• The easiest way to get the content of an element
is by using the innerHTML property.
• The innerHTML property is useful for getting or
replacing the content of HTML elements.
• The innerHTML property can be used to get or
change any HTML element, including <html> and
<body>.
The HTML DOM Document Object

• The document object represents your web


page.
• If you want to access any element in an HTML
page, you always start with accessing the
document object.
• Below are some examples of how you can use
the document object to access and
manipulate HTML.
JavaScript Objects
• Real Life Objects, Properties, and Methods
• In real life, a car is an object.
• A car has properties like weight and color,
and methods like start and stop:

• ObjectProperties
1.car.name = Fiat 2.car.model = 500
3.car.weight = 850kg 4.car.color = white

• Methods
1.car.start() 2.car.drive()
3.car.brake() 4.car.stop()
• All cars have the same properties, but the
property values differ from car to car.
• All cars have the same methods, but the
methods are performed at different times.
• JavaScript Objects
• You have already learned that JavaScript
variables are containers for data values.
• This code assigns a simple value (Fiat) to
a variable named car:
• <!DOCTYPE html>
• <html>
• <body>
• <p>Creating a JavaScript Variable.</p>
• <p id="demo"></p>
• <script>
• var car = "Fiat";
• document.getElementById("demo").innerHTML =
car;
• </script>
• </body>
• </html>
• Objects are variables too. But objects can contain many values.
• This code assigns many values (Fiat, 500, white) to a variable named
car:
• <!DOCTYPE html>
• <html>
• <body>
• <p>Creating a JavaScript Object.</p>
• <p id="demo"></p>
• <script>
• var car = {type:"Fiat", model:"500", color:"white"};
• document.getElementById("demo").innerHTML = car.type;
• </script>
• </body>
• </html>

• The values are written as name:value pairs (name and value


separated by a colon).
Object Properties
• The name:values pairs (in JavaScript objects)
are called properties.
• var person = {firstName:"John",
lastName:"Doe", age:50, eyeColor:"blue"};
• Object Methods:
• Methods are actions that can be performed on
objects.
• Methods are stored in properties as function
definitions.
Object Definition
• You define (and create) a JavaScript object with
an object literal:
• Example
• var person = {firstName:"John",
lastName:"Doe", age:50, eyeColor:"blue"};
• var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
Accessing Object Properties

• You can access object properties in two ways:


• objectName.propertyName
Or
objectName["propertyName"]
• Example1
• person.lastName;
• Example2
• person["lastName"];
• <!DOCTYPE html>
• <html>
• <body>
• <p>
• There are two different ways to access an object property:
• </p>
• <p>You can use person.property or person["property"].</p>

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

• <script>
• var person = {
• firstName: "John",
• lastName : "Doe",
• id : 5566
• };
• document.getElementById("demo").innerHTML =
• person.firstName + " " + person.lastName;
• </script>

• </body>
• </html>
• <!DOCTYPE html>
• <html>
• <body>

• <p>
• There are two different ways to access an object property:
• </p>
• <p>You can use person.property or person["property"].</p>

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

• <script>
• var person = {
• firstName: "John",
• lastName : "Doe",
• id : 5566
• };
• document.getElementById("demo").innerHTML =
• person["firstName"] + " " + person["lastName"];
• </script>

• </body>
• </html>
Accessing Object Methods

• You access an object method with the


following syntax:
• objectName.methodName()
• Example
• name = person.fullName();
• <!DOCTYPE html>
• <html>
• <body>

• <p>Creating and using an object method.</p>

• <p>An object method is a function definition, stored as a property value.</p>

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

• <script>
• var person = {
• firstName: "John",
• lastName : "Doe",
• id : 5566,
• fullName : function() {
• return this.firstName + " " + this.lastName;
• }
• };

• document.getElementById("demo").innerHTML = person.fullName();
• </script>
• </body>
• </html>
The Form Object
• Two aspects of the form can be manipulated through
JavaScript. First, most commonly and probably most
usefully, the data that is entered onto your form can be
checked at submission. Second you can actually build
forms through JavaScript.
• Form object supports three events to validate the form
onClick = “method()”
• This can be applied to all form elements. This event is
triggered when the user clicks on the element.
onSubmit = “method()”
• This event can only be triggered by form itself and occurs
when a form is submitted.
onReset = “method()”
• This event can only be triggered by form itself and occurs
when a form is reset.
The browser Object
• The browser is JavaScript object that can be
used to know the details of browser. Some of
the properties of the browser object is as
follows:
Property Description
navigator.appCodeName It returns the internal name for the
browser. For major browsers it is Mozilla
navigator.appName It returns the public name of the browser –
navigator or
Internet Explorer
navigator.appVersion It returns the version number, platform
on which the browser is running.
navigator.userAgent The strings appCodeName and appVersion
concatenated
together
navigator.plugins An array containing details of all installed
plug-ins
Navigator.mimeTypes An array of all supported MIME Types
The Math Object

• The Math object holds all mathematical


functions and values. All the functions and
attributes used in complex mathematics must
be accessed via this object.
• Syntax:
• Math.methodname();
• Math.value;
Method Descri Example
ption
Math.abs(x) Returns the absolute value Math.abs(-20) is 20

Math.ceil(x) Returns the ceil value Math.ceil(5.8) is 6


Math.ceil(2.2) is 3
Math.floor(x) Returns the floor value Math.floor(5.8) is 5
Math.floor(2.2) is 2
Math.round(x) Returns the round value, Math.round(5.8) is 6
nearest integer value
Math.round(2.2) is 2
Math.trunc(x) Removes the decimal Math.trunc(5.8) is 5
places it returns only Math.trunc(2.2) is 2
integer value
Math.max(x,y) Returns the maximum Math.max(2,3) is 3
value
Math.max(5,2) is 5
Math.min(x,y) Returns the minimum Math.min(2,3) is 2
value
Math.min(5,2) is 2
Math.sqrt(x) Returns the square root of Math.sqrt(4) is 2
x
Math.pow(a,b) This method will compute the ab Math.pow(2,4) is 16
Math.sin(x) Returns the sine value of x Math.sin(0.0) is 0.0

Math.cos(x) Returns cosine value of x Math.cos(0.0) is 1.0

Math.tan(x) Returns tangent value of x Math.tan(0.0) is 0

Math.exp(x) Returns exponential value i.e ex Math.exp(0) is 1

Math.random(x) Generates a random number in between 0 Math.random()


and 1
Math.log(x) Display logarithmic value Math.log(2.7) is 1

Math.PI Returns a ∏ value a = Math.PI;


a = 3.141592653589793
The Date Object
• This object is used for obtaining the date and time. In JavaScript, dates
and times represent in milliseconds since 1st January 1970 UTC.
JavaScript supports two time zones: UTC and local. UTC is Universal
Time, also known as Greenwich Mean Time(GMT), which is standard
time throughout the world. Local time is the time on your System. A
JavaScript Date represents date from -1,000,000,000 to -
1,000,000,000 days relative to 01/01/1970.
• Date Object Constructors:
• new Date(); Constructs an empty date object.
• new Date(“String”); Creates a Date object based upon the contents of
a text string.
• new Date(year, month, day[,hour, minute, second] ); Creates a Date
object based upon the numerical values for the year, month and day.

• var dt=new Date();


• document.write(dt); // Tue Dec 23 11:23:45 UTC+0530 2015
• <!DOCTYPE html>
• <html>
• <body>
• <p id="demo"></p>
• <script>
• document.getElementById("demo").innerHTML =
Date();
• </script>
• </body>
• </html>
output:
Mon Jan 29 2018 09:20:16 GMT+0530 (India
Standard Time)
JavaScript Date Methods
• Date methods let you get and set date values
(years, months, days, hours, minutes, seconds,
milliseconds)
Method Description

getDate() Get the day as a number (1-31)

getDay() Get the weekday as a number (0-6)

getFullYear() Get the four digit year (yyyy)

getHours() Get the hour (0-23)

getMilliseconds() Get the milliseconds (0-999)

getMinutes() Get the minutes (0-59)

getMonth() Get the month (0-11)


JavaScript Arrays
JavaScript arrays are used to store multiple values in a single
variable.

Displaying Arrays

<!DOCTYPE html>
<html>
<body>

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

<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>

</body>
</html> 76
Creating an Array Cont..
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array-name = [item1, item2, ...];
Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to it:
var cars = new Array("Saab", "Volvo", "BMW");
Access the Elements of an Array
You refer to an array element by referring to the index number.
var name = cars[0];
This statement modifies the first element in cars:
cars[0] = "Opel";
Can Have Different Objects in One Array
• JavaScript variables can be objects. Arrays are special kinds
of objects.
• Because of this, you can have variables of different types in
the same Array.
Example:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars; 77
Cont..
Arrays are Objects
• Arrays are a special type of objects. The typeof operator in
JavaScript returns "object" for arrays.
• But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this example,
person[0] returns John:
Array: var person = ["John", "Doe", 46];
Objects use names to access its "members". In this example,
person.firstName returns John:
Object: var person = {firstName:"John", lastName:"Doe“,
age:46};
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array
properties and methods:
Examples
var x = cars.length; // The length property returns the number
of elements in cars
var y = cars.sort(); // The sort() method sort cars in
alphabetical order
78
Cont..

Note:
❖ var points = new Array(); // Bad
❖ var points = []; // Good

When to Use Arrays? When to use Objects?


• JavaScript does not support associative arrays.
• You should use objects when you want the element names to be
strings.
• You should use arrays when you want the element names to be
sequential numbers.

79
Array Object Methods Cont..
Method Description

concat() Joins two or more arrays, and returns a copy of the joined arrays

indexOf() Search the array for an element and returns its position
join() Joins all elements of an array into a string
Search the array for an element, starting at the end, and returns
lastIndexOf()
its position

pop() Removes the last element of an array, and returns that element

Adds new elements to the end of an array, and returns the new
push()
length
reverse() Reverses the order of the elements in an array

shift() Removes the first element of an array, and returns that element

slice() Selects a part of an array, and returns the new array


sort() Sorts the elements of an array
splice() Adds/Removes elements from an array
toString() Converts an array to a string, and returns the result
Adds new elements to the beginning of an array, and returns the
unshift()
new length
valueOf() Returns the primitive value of an array 80
Cont..
Concat():Joins two or more arrays, and returns a copy of the
joined arrays.
Syntax: array.concat(array1,array2…..);
Ex:
var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var kai = ["Robin"];
var children = hege.concat(stale,kai);
indexOf():this method searches the array for the specified item, and
returns its position.
• The search will start at the specified position, or at the beginning if
no start position is specified, and end the search at the end of the
array.
Returns -1 if the item is not found.
If the item is present more than once, the indexOf method returns the
position of the first occurrence.
Syntax: array.indexOf(item);
Ex: var fruits=[“Banana”,Orange”,”Apple”,”Mango”];
var x=fruits.indexOf(“Apple”);
Here the value of x is:2 i.e. Apple is at position 2. 81
Cont..
Join():The join() method joins the elements of an array into a string, and
returns the string.
The elements will be separated by a specified separator. The default
separator is comma (,).
Syntax: array.join();
Ex: var fruits=[“Banana” Orange”,”Apple”,”Mango”];
var x=fruits.join();
the result of x will be Banana,Orange,Apple,Mango.
Slice(): The slice() method returns the selected elements in an array, as
a new array object.
The slice() method selects the elements starting at the given start
argument, and ends at, but does not include, the given end argument.
Syntax: array.slice (start, end);
Ex: var fruits=[“Banana”,Orange”,”Apple”,”Mango”];
var x=fruits.slice(1,3);
the result of x will be [Orange,Apple];
Splice(): The splice() method adds/removes items to/from an array, and
returns the removed item(s).
Syntax: array.splice(index,howmany,item1,item2….);
Ex: var fruits=[“Banana”,Orange”,”Apple”,”Mango”];
fruits.splice(2,1,”Lemon”,”Kiwi”);
the result of fruits will be [Banana,Orange,Lemon,Kiwi,Mango]
82
Cont..
Arrays Operations and Properties

• Declaring new empty array:


var arr = new Array();

• Declaring an array holding few elements:


var arr = [1, 2, 3, 4, 5];
• Appending an element / getting the last element:
arr.push(3);
var element = arr.pop();
• Reading the number of elements (array length):
arr.length;

• Finding element's index in the array:

arr.indexOf(1);

83
JavaScript Regular Expressions
• A regular expression is a sequence of characters that forms
a search pattern.
• The search pattern can be used for text search and text
replace operations.
Syntax
/pattern/modifiers;

Example:
var patt = /w3schools/I

✓ /w3schools/i is a regular expression.


✓ w3schools is a pattern (to be used in a search).
✓ i is a modifier (modifies the search to be case-insensitive)

84
Cont..
Using String Methods
In JavaScript, regular expressions are often used with the
two string methods: search() and replace().
❖ The search(pattern) method uses an expression to search for a
match, and returns the position of the match.
❖ The replace(pattern1, pattern2) method returns a modified
string where the pattern is replaced.
❖ The split(pattern) method
❖ The match(pattern) method searches for a matching pattern.
Returns an array holding the results, or null if no match is found.
Example
var str = "Visit W3Schools";
var n = str.search(/w3schools/i);
The result in n will be: 6
Example
var str = "Visit Microsoft!";
var res = str.replace(/microsoft/i, "W3Schools");
The result in res will be: Visit W3Schools! 85
Cont..
Regular Expression Modifiers

Modifiers can be used to perform case-insensitive more global


searches:
Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all matches
rather than stopping after the first match)
m Perform multiline matching

Regular Expression Patterns

Brackets are used to find a range of characters:


Expression Description
[abc] Find any of the characters between the
brackets
[0-9] Find any of the digits between the
brackets
(x|y) Find any of the alternatives separated
with |
86
Metacharacters are characters with a special meaning: Cont..

Metacharacter / Token Description


\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning or at the end
of a word
\uxxxx Find the Unicode character specified by the
hexadecimal number xxxx
^ Match at the start of the input string
$ Match at the end of the input string
* Match 0 or more times
+ Match 0 or more times
? Match 0 or 1 times

{n} Match the string n times


\D Match anything except for digits 87
Metacharacter / Token Description

\w Match any alphanumeric character or the underscore


\W Match anything except alphanumeric characters or
underscore
\S Match anything except for whitespace characters
[…] Creates a set of characters, one of which must match
if the operation is to be successful. If you need a
range of characters then separate the first and last
with a hypen: [0-9] or [D-G]
[^…] Creates a set of characters which doesnot match. If
any character in the set matches then the operation
has failed. This fails if any lowercase letter from d to q
is matched: [^d-q].

Quantifiers define quantities:


Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more
occurrences of n
n? Matches any string that contains zero or one Cont..
occurrences of n 88
Cont..
Using the RegExp Object
• In JavaScript, the RegExp object is a regular expression object
with predefined properties and methods.

Using test() / using exec()


• The test() method is a RegExp expression method.
• It searches a string for a pattern, and returns true or false,
depending on the result.
The following example searches a string for the character "e":

Example
var patt = /e/;
patt.test("The best things in life are free!");
(or)
/e/.test("The best things in life are free!")
Since there is an "e" in the string, the output of the code above will
be: true

89
constructor
• It returns a reference to the array function that
created the instance's prototype.
• Syntax
• Its syntax is as follows:
RegExp.constructor
• Return Value
• Returns the function that created this object's
instance.
• Example
Try the following example program.
<html>
<head>
<title>JavaScript RegExp constructor Property</title>
</head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
document.write("re.constructor is:" + re.constructor);
</script>
</body>
</html>
Output
• re.constructor is:function RegExp() { [native code]
global
global is a read-only boolean property of RegExp
objects. It specifies whether a particular regular
expression performs global matching, i.e.,
whether it was created with the "g" attribute.
Syntax
Its syntax is as follows:
RegExpObject.global
Return Value
Returns "TRUE" if the "g" modifier is set, "FALSE"
otherwise.
<html>
<head>
<title>JavaScript RegExp global Property</title>
</head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
if ( re.global ){
document.write("Test1 - Global property is set");
}else{
document.write("Test1 - Global property is not set");
}
re = new RegExp( "string", "g" );
if ( re.global ){
document.write("<br />Test2 - Global property is set");
}else{
document.write("<br />Test2 - Global property is not set");
}
</script>
</body>
</html>
Output
Test1 - Global property is not set
Test2 - Global property is set
ignoreCase
ignoreCase is a read-only boolean property of
RegExp objects. It specifies whether a
particular regular expression performs case-
insensitive matching, i.e., whether it was
created with the "i" attribute.
• Syntax
Its syntax is as follows:
• RegExpObject.ignoreCase
• Return Value
Returns "TRUE" if the "i" modifier is set,
"FALSE" otherwise.
<html>
<head>
<title>JavaScript RegExp ignoreCase Property</title>
</head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
if ( re.ignoreCase ){
document.write("Test1 - ignoreCase property is set");
}else{
document.write("Test1 - ignoreCase property is not set");
}
re = new RegExp( "string", "i" );
if ( re.ignoreCase ){
document.write("<br />Test2 - ignoreCase property is set");
}else{
document.write("<br />Test2 - ignoreCase property is not set");
}
</script>
</body>
</html>
Output
Test1 - ignoreCase property is not set
Test2 - ignoreCase property is set
lastIndex
lastIndex is a read/write property of RegExp
objects. For regular expressions with the "g"
attribute set, it contains an integer that specifies
the character position immediately following the
last match found by the RegExp.exec() and
RegExp.test() methods. These methods use this
property as the starting point for the next search
they conduct.
This property is read/write, so you can set it at
any time to specify where in the target string,
the next search should begin. exec() and test()
automatically reset the lastIndex to 0 when
they fail to find a match (or another match).
Syntax
Its syntax is as follows:
RegExpObject.lastIndex
Return Value
Returns an integer that specifies the character
position immediately following the last match.
<html>
<head>
<title>JavaScript RegExp lastIndex Property</title>
</head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
re.test(str);
document.write("Test 1 - Current Index: " + re.lastIndex);
re.test(str);
document.write("<br />Test 2 - Current Index: " + re.lastIndex);
</script>
</body>
</html>
Output
Test 1 - Current Index: 10
Test 2 - Current Index: 35
multiline
multiline is a read-only boolean property of
RegExp objects. It specifies whether a
particular regular expression performs
multiline matching, i.e., whether it was created
with the "m" attribute.
Syntax
Its syntax is as follows:
RegExpObject.multiline
Return Value
Returns "TRUE" if the "m" modifier is set, "FALSE"
otherwise.
<html>
<head>
<title>JavaScript RegExp multiline Property</title>
</head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
if ( re.multiline ){
document.write("Test1-multiline property is set");
}else{
document.write("Test1-multiline property is not set");
}
re = new RegExp( "string", "m" );
if ( re.multiline ){
document.write("<br/>Test2-multiline property is set");
}else{
document.write("<br/>Test2-multiline property is not
set");
}
</script>
</body>
</html>
Output
Test1-multiline property is not set
Test2-multiline property is set
Exception Handling
Try… Catch and Throw statements
Catching errors in JavaScript:
It is very important that the errors thrown must be catched or
trapped so that they can be handled more efficiently and
conveniently and the users can move better through the
web page.
Using try…catch statement:
The try..catch statement has two blocks in it:
· try block
· catch block
In the try block, the code contains a block of code that is to be
tested for errors.
The catch block contains the code that is to be executed if an
error occurs. The general syntax of try..catch statement is as
follows:
Exception Handling
throw
Example:
do something
if an error happens
{
create a new exception object
throw the exception
}

try……..
Example: try
{
statement one
statement two
statement three
}
catch
Example:
catch exception
{
handle the exception }
104
The concept of try…catch statement
<html>
<head>
<script type="text/javascript">
try
{
document.write(junkVariable)
}
catch(err)
{
document.write(err.message + "<br/>")
}
</script>
</head>
<body>
</body>
</html>
• The output of the above program is
‘junkVariable’ is undefined
• In the above program, the variable
junkVariableis undefined and the usage of this
in try block gives an error. The control is
transferred to the catch block with this error
and this error message is printed in the catch
block.
throw in JavaScript:
There is another statement called throw available
in JavaScript that can be used along
with try…catch statements to throw exceptions
and thereby helps in generating. General
• syntax of this throw statement is as follows:
throw(exception)
• exception can be any variable of type integer or
boolean or string.
<html>
<head>
<script type="text/javascript">
try
{
varexfor=10
if(exfor!=20)
{
throw "PlaceError"
}
}
catch(err)
{
if(err == "PlaceError")
document.write ("Example to illustrate Throw
Statement: Variable exfor not equal to 20.
<br/>")
}
</script>
</head>
<body>
</body>
</html>
The output of the above program is:
Example to illustrate Throw Statement: Variable exfor not equal to 20.
In the above example program, the try block has
the variable exfor initialized to 10. Using the if
statement, the variable value is checked to see
whether it is equal to 20. Since exfor is not
equal to 20, the exception is thrown using the
throw statement. This is named Place Error and
the control transfers to the catch block. The
error catched is checked and since this is equal
to the PlaceError, the statement placed inside
the error message is displayed and the output
is displayed as above.
Example: <!DOCTYPE html> Cont..
<html>
<body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "is Empty";
if(isNaN(x)) throw "not a number";
if(x > 10) throw "too high";
if(x < 5) throw "too low";
}
catch(err) {
message.innerHTML = "Input " + err;
}
}
</script></body></html> 110
Form validation program example
<html>
<head>
<script language="javascript">
function validate()
{

var x=f1.t1.value;
var y=f1.t2.value;
var re=/\d|\W|_/g;

if(x==''||y=='')
window.alert("Enter both user id and password");
else if(x.length<6||y.length<6)
window.alert("both user id and password should greater than or equal to 6");
else if((re.test(x)))
window.alert("user name show3uld be alphabets");
else
window.alert("welcome"+" Mr."+x);
}
</script>
</head>
<body bgcolor="green">
<form name="f1">
<center>
User Name<input type="text" name="t1"><br><br>
Password <input type="password" name="t2"><br><br>
<input type="submit" value="submit" onClick=validate()>
<input type="reset" value="reset">
</center>
</form>
</body>

</html>

You might also like