Unit 1 Client Side Scripting Latest
Unit 1 Client Side Scripting Latest
Unit 1 Client Side Scripting Latest
Basic Works in the back end which could not be visible at the client Works at the front end and script are visible
end. among the users.
Processing Requires server interaction. Does not need interaction with the server.
Languages PHP, ASP.net, Ruby on Rails, ColdFusion, Python, HTML, CSS, JavaScript, etc.
Affect Could effectively customize the web pages and provide Can reduce the load to the server.
dynamic websites.
Security Relatively secure. Insecure
➢ Client-side scripting is performed to generate a code that can run on the client end (browser) without needing
the server side processing. Basically, these types of scripts are placed inside an HTML document. The effective
client-side scripting can significantly reduce the server load. It is designed to run as a scripting language utilizing
a web browser as a host program. For example, when a user makes a request via browser for a webpage to the
server, it just sent the HTML and CSS as plain text, and the browser interprets and renders the web content in the
client end.
Client-Side Scripting language Vs Server-side Scripting language
➢ Server-side scripting is a technique of programming for producing the code which can run software on
the server side, in simple words any scripting or programming that can run on the web server is known as
server-side scripting, The server-side involves three parts: server, database, API’s and back-end web
software developed by the server-side scripting language. When a browser sends a request to the server
for a webpage consisting of server-side scripting, the web server processes the script prior to serving the
page to the browser. Here the processing of a script could include extracting information from a database,
making simple calculations, or choosing the appropriate content that is to be displayed in the client end.
The script is being processed and the output is sent to the browser. The web server abstracts the scripts
from the end user until serving the content, which makes the data and source code more secure.
Client-Side Scripting language
➢Advantages:
➢ More interactive since it responds immediately to the user action.
➢ Quick Execution because they don't require a trip to the server.
➢ improve the user experience for the user whose browser support script.
➢ An alternative option is available for the user whose browser didn't support script.
➢ Reusable and obtainable from many resources.
➢ Disadvantages:
➢ It is not supported by all browsers. if no alternative is given for the script than the user might get an error.
➢ Need more testing. because of the different browser and its version support script differently.
➢ If the Script is not available through other resources than more development time and effort required.
➢ Developers have more control over the look and behavior of their Web widgets; however, usability issues can arise if a
Web widget seems like a standard control but behaves different way or vice-versa.
Uses of JavaScript
➢ Adding Interactivity to the website:
➢ Developing mobile application:
➢ Create web browser-based games
➢ Back end web development:
➢ Client-side Validation:
➢ Event Handling:
➢ Building web servers and developing server applications:
➢ Some other uses:
➢Dynamic drop-down menus.
➢ Build forms that respond to user input without accessing a server.
➢ Change the appearance of HTML documents and dynamically write HTML into separate windows.
➢ Open and close new windows or frames.
➢ 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 date, clocks etc.
Formatting and Coding Convention
❑ Naming and declaration rules for variables and functions.
❑ Rules for the use of white space, indentation, and comments.
❑ Programming practices and principles
Coding conventions secure quality:
❑ Improves code readability
❑ Make code maintenance easier
❖ Mainly we use camelCase for identifier names (variables and functions) eg: firstName, doExit()
❖ Always put spaces around operators ( = + - * / ), and after commas: eg: var x = y + z;
❖ Always use 2 spaces for indentation of code blocks:
eg: function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
} }
❖ Always end a simple statement with a semicolon. (It’s a rule actually like in Java)
❖ Global variables written in UPPERCASE (We don't, but it's quite common)
❖ Constants (like PI) written in UPPERCASE
JavaScript Files, Comments
We should always include in the head so that the browser is ready to execute scripts when the user calls for them . If a
user clicked a button that called for a script that the browser wasn’t aware of yet, you’d get an error. Having them in the
head means they’re always ready before they’re needed.
A Simple Script
<script type=“text/javascript”>
document.write(“<h1> Title</h1>”);
document.write(“<p align=‘right’>Body</p>”);
</script>
We start by taking control of the document object, and uses its write method to output some text to the document. The
text inside the double quotes is called a String, and this String will be added to the page. To use an object’s methods or
properties, we write the object’s name, a dot, and then the method/property name. Each line of script ends with a
semicolon.
Note that when quoting attributes values, we have to use single quotes, as if we used double quotes , as if you used double
quotes the write method would think the string was over prematurely, and you’d get an error.
Noscript
To find whether the browser supports JavaScript or not, use the <noscript> tag. The HTML <noscript> tag is used to
handle the browsers, which do recognize <script> tag but do not support scripting. This tag is used to display an alternate text
message.
Eg:-
<!DOCTYPE html>
<html>
<head>
<title>HTML noscript Tag</title>
</head>
<body>
<script>
<!--
document.write(“<h1 style=‘color: magenta’>Welcome to JavaScript!</h1>")
-->
</script>
<noscript>
Your browser does not support JavaScript!
</noscript>
</body>
</html>
Basic Display Function in JS
document.write() : This is used to display given text on a webpage in JS.
<script>
document.write(“Welcome to JavaScript”);
</script>
console.log(): This function in JavaScript which is used to print any kind of variables defined before in it or to just print any
message that needs to be displayed to the user
<script>
console.log(“Welcome to JavaScript”);
</script>
Variables in JS
❑ Variables are containers for storing data values.
❑ JS variable is loosely typed language means a variable can store any type of value.
❑ Var keyword is used to declare variable. Eg: var name=“Ram”; var age=25;
❑ Variable scope in JS.
❑ Global Scope: variable declared outside of any function is global variables. It can be accessed & modified from any functions.
❑ Local Scope: Variables declared inside of any function is local variables. It can’t be accessed & modified outside functions
declaration.
❑ Eg:
<script type="text/javascript">
var fname="Java";
function name(){
var lname="Script“;
document.write(fname+lname);
}
document.write(fname+"<br>"); // we can't insert lname;
fname="ram";
lname="peter";//can't edit.
name();
</script>
Variables in JS
Var Let Const
var == function scope let == block scope const == block scope like let but immutable
Function scope means it occurs within a Block scope means it occurs within a Like let, const also uses block scope. But
function code block. const creates a constant, an immutable
Function scope is within the function. Block scope is within curly brackets. variable whose value cannot be changed.
<script type="text/javascript">
var fname;
var fname="mohan";
let age=30;
//let age=50; we can't use let to declare same variable
fname="Java"; //or var fname="java";
const name="Sohan"; //
/* const name;
name="sohan"; we can't do this */
{
var y=5; let x=6;
x=7;//we can modify value of let variable
document.write(x+"<br>");
}
document.write(y+" "+name+" "+age+" "+fname);
document.write(x);// let is block level variable
</script>
Operations
Variables:
• A variable is a location in the computer’s memory where a value can be stored for use by a script.
• All variable have a name and a value.
• Before 2015, using the var keyword was the only way to declare a JavaScript variable.
• The 2015 version of JavaScript (ES6 - ECMAScript 2015) allows the use of the const keyword to define a variable that cannot
be reassigned, and the let keyword to define a variable with restricted scope.
example : var price1 = 5; var price2 = 6; var total = price1 + price2;
Operators Operator Description Operator Example Same As
+ Addition = x=y x=y
- Subtraction += x += y x=x+y
Arithmetic * Multiplication -= x -= y x=x-y Assignment
Operator Operator
** Exponentiation Math.pow(x,y) *= x *= y x=x*y
/ Division /= x /= y x=x/y
% Modulus (Division Remainder) %= x %= y x=x%y
++ Increment **= x **= y x = x ** y
-- Decrement = x=y x=y
Operations
Operators
+ operator can be used to concatenate String. Eg: var a=“5”; var b=“Script”; var c=a+b;
var day=1;
switch(day)
{
case 1:
document.write("<h1 style='color:blue'>Sunday</h1>");
break;
case 2:
document.write("<h1 style='color:green'>Monday");
break;
case 3:
document.write("<h1 style='color:yellow'>Tuesday");
break;
case 4:
document.write("<h1 style='color:magenta'>Wednesday");
break;
case 5: case 7:
document.write("<h1 style='color:black'>Thursday"); document.write("<h1 style='color:green'>Saturday");
break; break;
case 6: default:
document.write("<h1 style='color:purple'>Friday"); document.write("<h1 style='color:red'>InValid Input");
break; }
</script>.
Control Structures
WAP to find day of a week using Switch case
<html>
<head>
<title>doWhileExercise</title>
</head>
<body bgcolor="green">
<script type="text/javascript">
var i=12;
do{
document.write("<p style='font-size:"+i+"'>This is testing ");
i=i+3;
}while(i<30);
</script>
</body>
</html>
Labeled Statement
• Break: Jumps out of the loop/break the loop
• Continue: breaks one iteration of the loop and continue with the execution of loop.
• Label: javascript label statements are used to prefix a label to an identifier. A label can be used with break and continue
statement to control the flow more precisely. A label is simply an identifier followed by a colon (:) that is applied to a
statement or a block of code.
<script>
var i, j;
loop1:
for (i = 0; i < 3; i++) { //The first for statement is labeled "loop1"
loop2:
for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2"
if (i === 1 && j === 1) {
continue loop1;
}
console.log('i = ' + i + ', j = ' + j);
}
} Output using
</script> Output using Loop 1
Loop 2
Array
❑ Array JavaScript Array is like a data type that is used to store one or more than one value of a similar type together.
❑ In simple, An array is a collection of variables of the same type.
❑ An array in javascript is an Array object. We use new operator to create an array and to specify the number of elements
in an array.
❑ Declaring and Allocating arrays :
var c; //declares a variable that will hold the array.
c=new Array(12); //allocates the array
The preceding statements can also be performed in single steps,
var c=new Array(12);
❑ Array using literal notation:
var earray = [ ]; // empty array
var fruits = ["mango","apple","orange","guava"]; // Array having elements
❑ Using new key word
let arr = new Array(); // empty array
let arr = new Array(10); // array of 10 elements size
let arr = new Array("Java","C","C++"); // array with 3 values
Foreach loop
❑ To loop over an array, we can also use the Array function forEach which is defined in its prototype definition.
Array Method:
var arr=new Array(“ram”, ”Shyam”, “hari”, “Geeta”);
• delete() : delete arr[index] ;
• Push() : arr.push(“Laxman”);
• Pop() : arr.pop();
• Sort() : arr.sort();
• Reverse() : arr.reverse();
• Shift() : insert item at first
• Unshift() : arr.unshift(“Peter”); delete item from first
• Concat() : arr1.concat(arr2);
Foreach loop
❑ To loop over an array, we can also use the Array function forEach which is defined in its prototype definition.
<script type="text/javascript">
var a=5;//no scope let a1=6;// within Scope
var sub=["java","Php","JavaScript"];
document.writeln("<h2 style='color:Magenta'>First Stage<h2>");
sub.forEach(function(value, index){
document.write("<h3 style='color:Yellow'>"+index+":"+value+"<br>");
});
document.write("<h2 style='color:Magenta'>Second Stage<h1>");
sub.push("Python");// used to insert item at last
sub.unshift("DataStructure"); //used to insert item at first
sub.forEach(function(value, index){
document.write("<h3 style='color:Yellow'>"+index+":"+value+"<br>");
});
document.write("<h2 style='color:Magenta'>Third Stage<h1>");
sub.pop(1); //used to remove item
sub.forEach(loop);
function loop(value, index){
document.write("<h3 style='color:Yellow'>"+index+":"+value+"<br>");
};
document.write("<br>"+sub.reverse());
document.write(sub.indexOf("JavaScript"));
</script>
for-of loop & for-in loop
▪ for/in - loops through the properties of an object
▪ for/of - loops through the values of an iterable object
▪ Difference with example :
<script type="text/javascript">
var mobile=['samsung','iphone','huwaei','MI'];
var y;
document.write("<h1>For Of Loop Start</h1>");
for(y of mobile){
document.write("<h2 style='color:orange'>"+y+"<br>");
}
document.write("<h1>For In Loop Start</h1>");
for(var x in mobile){
document.write("<h2 style='color:orange'>"+x+"<br>");
}
</script>
Defining and Invoking functions
❑ Function are subprogram which are used to compute a value or perform a task.
❑ It is a set of statements that are used to perform a specific task, like adding two numbers, finding the square of a
number, or any user-defined task.
❑ Functions can be parameterized and non-parameterized which means they may or may not take any input.
❑ There are two types of function in JavaScript
➢ Library or Built-in function. Eg: write(), alert(), prompt(), parseInt()
➢ User defined function:
❑ Function is defined by using the function keyword followed by the function name and parentheses ( ), to hold
params(inputs) if any. A function can have zero or more parameters separated by commas.
❑ The function body is enclosed within curly braces just after the function declaration part(function name and params), and
at the end of the function body, we can have a return statement to return some output, if we want.
function function_name(parameter-1, parameter-2,...parameter-n) {
// function body }
❑ Calling a user defined function:
After creating a function, we can call it anywhere in our script. The syntax for calling a function is
function_name(val-1, val-2, ..., val-n);
Defining and Invoking functions
❑ Return statement: A function may have return statement i.e., function may return value depending on the requirement.
WAP to implement simple function WAP to implement simple function with return type
<script type="text/javascript">
<script type="text/javascript">
function add(a,b){
function add(a,b){
var c=a+b;
var c=a+b;
return c;
document.writeln("The total is:"+c);
}
}
var r1=add("romeo", "Juliet");
add("romeo", "Juliet");
document.write(r1);
document.write("<br>");
document.write("<br>");
add(2,3);
var r2=add(2,3);
</script>
document.write(r2);
</script>
Defining and Invoking functions
❑ Functions can also be defined with a built-in JavaScript function constructor called Function().
WAP to implement function using constructor We actually don't have to use the function constructor.
var funct = new Function("a", "b", "return a * b"); var funct = Function("a", "b”, “return a*b”);
var x = funct(5, 6); var x = funct(5, 6);
document.write(x); document.write(x);
</script> </script>
Build in Objects, Date Objects
❑ An object as a collection of properties that are defined as a key-value pair, where the key is the generic name of the
object feature which can be assigned a value.
❑ In JavaScript, an object is a standalone entity where the properties of the object define the characteristics of the object.
❑ For example, if we consider a mobile phone as an object then its properties are its color, screen size, brand name,
operating system, RAM, Memory, etc. All these properties define the characteristics of a mobile phone.
❑ The property of an object is a key: value pair, where key refers to a variable, and value refers to any type of value
associated with the key. The value can be of any type like a number, string, or even an array, or another object.
❑ Build in Object:
➢ Math Object: abs(x), ceil(x), cos(x), floor(x), log(x), min(x, y), pow( x, y), round(x), sqrt(x)
➢ String Object: we will see in detail:
➢ Date Object:
➢ User defined Object
➢ Boolean Object
➢ Number Object
Build in Objects, Date Objects
❑ Wap to show program on userdefined object
<script type="text/javascript">
//let mobile =new object(),
let mobile={
name:'iphone', //first property has key: name & value:iphone
brand:'Apple',
model:'iphone XS-max',
price:150000
};
mobile.color="Black"; //adding new property to mobile
mobile['screen']="6.5in";
document.write("<h1 style='color:magenta'>"+mobile.name+"</h1>"); //access using property name.value
document.write("<h1 style='color:yellow'>"+mobile['brand']+"</h1>");
document.write("<h1>"+mobile['color']+"</h1>");
document.write("<h1 style='color:#aabbcc'>"+mobile['screen']+"</h1>");
delete mobile.brand; //remove property
mobile.model="Iphone XI-Max Pro"; //update the value of model
for(key in mobile){ //transversing object
document.write("<h1 style='color:#ddeeff'>"+mobile[key]+"<br>");
}
Strings
❑ String is simply a groups of characters, a word, sentence or URL for example .
❑ String are always delimited by quotes, either single or double. Usually you can single quotes around single character and
double quotes around anything longer. Eg: var a=“Welcome to the”; var b = “java Script”;
❑ To concatenate, or joint two strings, we use a plus sign. Eg: document.write(a+’ ‘+b);
❑ String has many methods and properties.
Methods Function
concat() It provides a combination of two or more strings.
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string by searching a character from the last position.
search() It searches a specified regular expression in a given string and returns its position if a match occurs.
substr() It is used to fetch the part of the given string on the basis of the specified starting position and length.
substring() It is used to fetch the part of the given string on the basis of the specified index.
slice() It is used to fetch the part of the given string. It allows us to assign positive as well negative index.
trim() It trims the white space from the left and right side of the string.
Method Description
alert() displays the alert box containing message with ok button.
confirm() displays the confirm dialog box containing message with ok and cancel button.
performs action after specified time like calling function, evaluating expressions etc.
setTimeout()
It performs its task after the given milliseconds.
Interacting with Browser, Windows & Frames – Windows & frames
<script type="text/javascript">
function myFunction(){ <body bgcolor="green">
var x=prompt("Enter value of x:"); <button onclick="myFunction()">Pro_Alert</button>
var y=prompt("Enter value of y:"); <button onclick="myFunction1()">Con_SetTout</button>
if(x>y) <button onclick="myFunction2()">Open</button>
alert("x is greater:"); <button onclick="myFunction3()">close</button>
else </body>
alert("y is greater:");
}
function myFunction1(){
var click=confirm("Would you like to submit");
setTimeout( function() {
if(click==true)
alert("you have submitted");
else
alert("not submitted");
}, 2000);
}
function myFunction2(){
open("date.html","myWindow","width=400, height=600");
}
function myFunction3(){
close();
}
</script>
</head>
Interacting with Browser, Windows & Frames -History
❑ The JavaScript history object represents an array of URLs visited by the user. By using this object, you can load previous,
forward or any page.
❑ Property of JavaScript history object :
• length: It returns the length of the history URLs visited by user in that session.
❑ Methods: forward(), back(), go()
<script type="text/javascript">
function backFunction() {
window.history.back(); //history.back();
}
function forwardFunction() {
window.history.forward();
}
function forward2Function() {
window.history.go(2);
}
</script>
</head>
<body bgcolor="green">
<button onclick="backFunction()">Back</button>
<button onclick="forwardFunction()">Forward</button>
<button onclick="forward2Function()">Forward2</button>
</body>
Interacting with Browser, Windows & Frames -Navigator
❑ The JavaScript navigator object is used for browser detection. It can be used to get browser information such as appName,
appCodeName, userAgent etc.
<script type="text/javascript">
document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);
document.writeln("<br/>navigator.appName: "+navigator.appName);
document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);
document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);
document.writeln("<br/>navigator.language: "+navigator.language);
document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
document.writeln("<br/>navigator.platform: "+navigator.platform);
document.writeln("<br/>navigator.onLine: "+navigator.onLine);
if(navigator.cookieEnabled==true){
alert("cookies enabled");
}
else{
alert("Cookies disabled");
}
</script>
Interacting with Browser, Windows & Frames -Screen
❑ The JavaScript screen object holds information of browser screen. It can be used to display screen width, height,
colorDepth, pixelDepth etc..
<script>
document.writeln("<br/>screen.width: "+screen.width);
document.writeln("<br/>screen.height: "+screen.height);
document.writeln("<br/>screen.availWidth: "+screen.availWidth);
document.writeln("<br/>screen.availHeight: "+screen.availHeight);
document.writeln("<br/>screen.colorDepth: "+screen.colorDepth);
document.writeln("<br/>screen.pixelDepth: "+screen.pixelDepth);
</script>
❑ Location Object : The window.location object can be used to get the current page address
(URL) and to redirect the browser to a new page.
window.location.href : returns the href (URL) of the current page
window.location.hostname : returns the domain name of the web host
window.location.pathname : returns the path and filename of the current page
window.location.protocol : returns the web protocol used (http: or https:)
window.location.assign(): loads a new document
window.location.reload(): reload document
Document Object Model
❑ The Document Object Model or DOM is tree of nodes/elements created by the browser when a webpage is loaded.
❑ Its like a tree of elements also called nodes, which are used to represent every single element on the page.
❑ JavaScript Document object is an object that provides access to all HTML elements of a document.
❑ The document object stores the elements of an HTML document, such as HTML, HEAD, BODY, and other HTML tags as
objects.
❑ A document object is the child object of the window object
❑ What can we do using DOM?
➢ JS help us to change all elements, attributes, CSS styles in the page.
➢ Attach event listeners to elements (click, keypress, submit).
➢ JS helps us to add new HTML elements and attributes.
➢ JS helps us to remove existing HTML elements and attributes.
Document Object Model
HTML DOM tree of Objects
Element Node
Attribute Node
Text Node
Document Object Model
<html>
<head>
<meta charset="utf-8">
<title>DOM Tree Demos</title>
</head>
<body bgcolor="green">
<h1>An HTML 5</h1>
<p> This page contains some basic
HTML5 elements</p>
<p>Here's an unordered list:</p>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</body>
</html>
• The html node at the top of the tree is called the root node.
• The head and body node are siblings, since they’re both children of the html node. The head contain meta and title nodes. The body
node contains nodes representing each of the elements in the document’s body element.
• The li nodes are children of the ul node, since they’re nested inside it.
Document Object Model
❑ The Document Object Model or DOM is tree of nodes/elements created by the browser when a webpage is loaded.
❑ The Document Object Model (DOM) is a programming interface for HTML and XML(Extensible markup language)
documents.
❑ DOM is a way to represent the webpage in the structured hierarchical way so that it will become easier for programmers
and users to glide through the document. With DOM, we can easily access and manipulate tags, IDs, classes, Attributes or
Elements using commands or methods provided by Document object.
❑ Methods of Document Object:
innerHTML: Gets or sets HTML or XML markup contained within the element
get/setAttributeNode: To get and set attribute node with property and value
mouseover onmouseover When the cursor of the mouse comes over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
<body bgcolor="green">
<div>
<label id="lbl">Input Name:</label>
<input type="text" id="txt">
<input type="text" id="txt1"><br><br>
<button id="btn">Click</button>
<button id="btn1">Click1</button>
</div>
Event Handling
<script>
document.getElementById("btn").onmousemove=fun;
function fun(){document.getElementById("txt").style.background="blue"};
document.getElementById("btn1").addEventListener("dblclick",fun1);
function fun1(){ document.getElementById("lbl").style.border="5px solid red"};
document.getElementById("lbl").addEventListener("mousemove",function(){
this.style.background="yellow";
});
document.getElementById("txt1").addEventListener("mouseleave",fun2);
function fun2(){
this.style.background="blue";
};
document.getElementById("txt1").addEventListener("click",function(){
this.removeEventListener("mouseleave",fun2);
});
</script>
</body>
Forms
❑ Forms are used in webpages for the user to enter their required details that further send it to the server for processing. A
form is also known as a web form or HTML form. Examples of form use are prevalent in e-commerce websites, online
banking, online surveys to name a few.
Accessing the Form Elements: CheckBox
function fun1(){
var chkbx=document.getElementsByClassName("abc");
if(chkbx[0].checked==true){
document.getElementById("para").style.color="yellow";
}
else{
document.getElementById("para").style.color="black";
}
if(chkbx[1].checked==true){
document.getElementById("para").style.fontSize="50px"
}
if(chkbx[2].checked==true){
document.getElementById("para").style.fontWeight="bold";
}
}
<form onclick="fun1()">
<input id="rd1" name="group1" type="radio" value="male">Male<br>
<input id="rd2" name="group1" type="radio" value="female">Female<br>
<button >Clickme</button>
</form>
COOKIES
❑ A cookie is a piece of data that is stored on your computer to be accessed by your browser.
❑ A cookie contains the information as a string generally in the form of a name-value pair separated by semi-colons.
❑ It maintains the state of a user and remembers the user's information among all the web pages.
❑ Why Cookies?
❑ The communication between a web browser and server happens using a stateless protocol named HTTP. Stateless
protocol treats each request independent. So, the server does not keep the data after sending it to the browser. But
in many situations, the data will be required again. Here come cookies into a picture. With cookies, the web browser
will not have to communicate with the server each time the data is required. Instead, it can be fetched directly from
the computer. whenever a user sends a request to the server, the cookie is added with that request automatically.
Due to the cookie, the server recognizes the users.
❑ Structure of Cookies :
❑ Cookies are created using the cookie property of the Document object.
❑ The format of a cookie is as follows:
the name and value settings can be anything you choose to use. Eg: name=“ram” or any variable. This is the only section of the
cookie that is mandatory.
▪ expires=expirationDateGMT; : The optional expires= section specifies the date on which the cookie should expire. The
JavaScript Date Object can be used to obtain and manipulate dates for this purpose
e.g.: var expirationDate = new Date; expirationDate.setMonth(expirationDate.getMonth()+6)
▪ path=URLpath; : The path= setting allows a URL to be stored in the cookie. By default, cookies are accessible only to web
pages in the same directory as the web page which originally created the cookie. For example, if the cookie was created when the
user loaded http://www.hamronepal.com/home/index.html that cookie will be accessible to any other pages in the /home
directory, but not to pages in /about. Usually, we should set path to the root: path=/ to make the cookie accessible from all
website pages.
▪ domain=siteDomain : It specifies the domain for which the cookie is valid. If not specified this defaults to the host portion of
the current document location. If a domain is specified, sub domains are always included.
eg: document. Cookie =“username=peter; domain=peterson.com”;
person1.peterson.com person2.peterson.com //this two sub domain can access cookie made by domain=peterson.com
eg: document. Cookie =“username=peter; domain=person3.peterson.com”; //peterson.com can’t access cookie made by person3
COOKIES
<script>
function cookfun(){
var ucookval=document.getElementById("uname").value;
//=document.frm.uname.value;
var pcookval=document.getElementById("pass").value;
//=document.frm.pass.value;
//create cookie
document.cookie="Username = "+ucookval+";"+"expires=Thu, 18 Dec 2021 12:00:00 UTC";
document.cookie="Password= "+pcookval+";"+"expires=Thu, 18 Dec 2021 12:00:00 UTC";
}
//retrieve cookie
function cookfun1(){
var cookArr=document.cookie.split(";");
for(var i=0;i<cookArr.length;i++){
var cookVal=cookArr[i].split("=");
if(cookVal[0].trim()=='Username'){
//document.frm.uname.value=cookVal[1];
document.getElementById("uname").value=cookVal[1];
}
COOKIES
else if(cookVal[0].trim()=='Password'){
//document.frm.pass.value=cookVal[1];
document.getElementById("pass").value=cookVal[1];
} }
}
</script>
</head>
<body bgcolor="green">
<form name="frm">
Username: <input type="text" name="uname" id="uname"><br><br>
Password: <input type="text" name="pass" id="pass"><br><br>
<button onclick="cookfun()">SetCookie</button>
<button onclick="cookfun1()">GetCookie</button>
</form>
</body>
Handling Regular Expression
▪ Regular expressions are patterns used to match character combinations in strings.
▪ In JavaScript, regular expressions are also objects.
▪ Some methods of Regular expression:
▪ Exec(): this function will return an array for match or null if there is no matching.
▪ Test(): this function returns true or false
▪ Match() : this function returns an array of result or null
▪ Search() : this function returns index of first match else -1
▪ Replace() : This function returns new replaced string with all replacements( if no flag is given first match will be replaced)
▪ Flags:
▪ g – Global search, don’t return after the first match
▪ i – Case-insensitive search
Handling Regular Expression
<script type="text/javascript">
let reg=/Nepal/gi; //this is regular expression literal
let s="The Nepal is a landlocked country nepal lies in south east Asia";
//exec method - returns an array for match or null if not match
console.log(reg.exec(s));
//test method- returns true or false
console.log(reg.test(s));
//match method - returns an array for match or null
console.log(s.match(reg));
//search method - returns index of first match otherwise -1
console.log(s.search(reg));
//replace method- returns new replaced string
console.log(s.replace(reg,'Nepal with Kalapani & Limpiyadhura'));
</script>
Handling Regular Expression
Meta-Characters:
Metacharacter Description
. Find a single character, except newline or line terminator
\w or [a-zA-Z0-9_] Matches any word Character. A word character is any letter, digit and underscore.
\W Find a non-word character
\d or [0-9] It matches any decimal digit from 0 through 9.
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word, beginning like this: \bHI, end like this: HI\b
\B Find a match, but not at the beginning/end of a word
\0 Find a NULL character
\n Find a new line character
\t Find a tab character only
[^aeiou] matches a single character outside the given set
(foo|bar|baz) matches any of the alternatives specified
Handling Regular Expression
Quantifiers: They are symbols that have a special meaning in a regular expression.
Symbol Description
n+ Matches any string that contains at least one n