Chapters
Chapters
In JavaScript,
regular expressions are also objects. These patterns are used with the exec and test methods
of RegExp, and with the match, matchAll, replace, search, and split methods of String. This
chapter describes JavaScript regular expressions.
Syntax
/pattern/modifiers;
RegularExp.html
Brackets
Brackets are used to find a range of characters:
Expression Description
[^0-9] Find any character NOT between the brackets (any non-digit)
(x|y) Find any of the alternatives specified
Metacharacters
Metacharacters are characters with a special meaning:
Metacharacter Description
\d Find a digit
Quantifiers
The frequency or position of bracketed character sequences and single characters can
be denoted by a special character. Each special character has a specific connotation.
The +, *, ?, and $ flags all follow a character sequence.
1
p+
It matches any string containing one or more p's.
2
p*
It matches any string containing zero or more p's.
3
p?
It matches any string containing at most one p.
4
p{N}
It matches any string containing a sequence of N p's
5
p{2,3}
It matches any string containing a sequence of two or three p's.
6
p{2, }
It matches any string containing a sequence of at least two p's.
7
p$
It matches any string with p at the end of it.
8
^p
It matches any string with p at the beginning of it.
Comparison chart:
BASIS FOR
STATIC BINDING DYNAMIC BINDING
COMPARISON
Event Occurrence Events occur at compile time are Events occur at run time are
time. time.
Loops in JavaScript
Looping in programming languages is a feature which facilitates the execution of a set
of instructions/functions repeatedly while some condition evaluates to true. For
example, suppose we want to print “Hello World” 10 times. This can be done in two
ways as shown below:
Iterative Method
Iterative method to do this is to write the document.write() statement 10 times.
Loops in JavaScript
Loops are used to execute a specific statement for a given number of times. Loops are always
followed by some condition. JavaScript provides all the basic loops that other programming
languages have.
while loop
while loop checks for a given condition to be true to execute statements that it contains within it.
When the condition becomes false, while loop break the execution of statements.
Syntax
initializer;
while(condition)
statement-1;
statement-2;
.....
modifier;
initializer is a variable that is tested within the condition. modifier modifies the initializer so that
the condition becomes false at some point.
Note: Make sure that your condition goes false somehow else you will be in an infinite loop.
VAPM,Almala Page 1
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Example
<script>
var i = 0;
while(i<6)
document.write(i);
document.write("<br />");
i++;
</script>
do while loop
do while loop first execute the statements that it contain and then check for a condition. So even
if the condition is false do-while loop is going to run at least once.
Syntax
initializer;
do
statement-1;
statement-2;
.....
modifier;
VAPM,Almala Page 2
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
while(condition);
Example
<script>
var i = 5;
do
document.write(i);
document.write("<br />");
i++;
while(i<6);
</script>
for loop
for loop is generally used when the number of iterations/repetitions are already known. Its not
that such tasks can't be done by while loop but its just a matter of preference.
Syntax
VAPM,Almala Page 3
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
statement-1;
.....
Here, initializer is a variable that is defined once in the beginning of a for loop. It is optional and can be
ignored. condition is checked after initialization. Then statements are executed and finally modifier
modifies the initializer. After that again condition is checked and the process continues. Modifier can also
be ignored.
You can drop the curly braces if only one statement is within the for loop.
Syntax
<script>
for(var i=0;i<10;i++)
document.write(i);
document.write("<br />");
</script>
Nested Loops
Any loop can be inserted inside any other loop. This is called nesting. for loop can be nested
inside while or for loop. Similarly while loop can be nested inside for loop or another while loop.
Syntax
VAPM,Almala Page 4
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
while(condition)
statements;
Example
<script>
var i,j;
for(i=0;i<3;i++)
document.write("<br />");
for(j=0;j<3;j++)
document.write("<br />");
document.write("<br />");
VAPM,Almala Page 5
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
/*************output***************
Outer Loop : 0
Inner Loop : 0
Inner Loop : 1
Inner Loop : 2
Outer Loop : 1
Inner Loop : 0
Inner Loop : 1
Inner Loop : 2
Outer Loop : 2
Inner Loop : 0
Inner Loop : 1
Inner Loop : 2
***********************************/
</script>
Can you guess how above loop works? First outer for loop initializes i, checks for the condition
then executes its first two statements. After that inner for loop starts to work. After executing its
statements 3 times, outer for loop is given the control again. And the process is repeated.
VAPM,Almala Page 6
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Loop control statements deviates a loop from its normal flow. All the loop control statements are
attached to some condition inside the loop.
break statement
break statement is used to break the loop on some condition.
Syntax
if(condition)
break;
statements;
while(condition)
if(condition)
break;
VAPM,Almala Page 7
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
statements;
Example
<script>
for(var i=1;i<10;i++)
if(i===7) break;
/**********output***********
***************************/
</script>
VAPM,Almala Page 8
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
for loop should print from 1 - 10. But inside loop we have given a condition that if value of i
equals to 7, then break out of loop. I have left the curly braces within the if condition because
there is only one statement to be executed.
Remember break burst the nearest for loop within which it is contained. To understand what
it means check out the next example.
Example
<script>
for(var i=1;i<=3;i++)
for(var j=1;j<=3;j++)
if(j===2)
break;
document.write("<br />");
VAPM,Almala Page 9
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
/**********output***********
Outer Loop : 1
Inner Loop : 1
Inner Loop : 2
Outer Loop : 2
Inner Loop : 1
Inner Loop : 2
Outer Loop : 3
Inner Loop : 1
Inner Loop : 2
***************************/
</script>
continue statement
continue statement is used to skip an iteration of a loop.
Syntax
if(condition)
VAPM,Almala Page 10
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
continue;
statements;
while(condition)
if(condition)
continue;
statements;
Example
<script>
for(var i=0;i<10;i++)
VAPM,Almala Page 11
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
/**********output***********
***************************/
</script>
In the code above when the value of i becomes 3 or 7, continue forces the loop to skip without
further executing any instructions inside the for loop in that current iteration.
Remember continue skips the nearest loop iteration within which it is contained. To
understand what it means check out the next example.
Example
<script>
for(var i=1;i<=3;i++)
VAPM,Almala Page 12
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
for(var j=1;j<=3;j++)
if(j===2)
continue;
document.write("<br />");
/**********output***********
Outer Loop : 1
Inner Loop : 1
Inner Loop : 3
Outer Loop : 2
Inner Loop : 1
Inner Loop : 3
VAPM,Almala Page 13
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Outer Loop : 3
Inner Loop : 1
Inner Loop : 3
***************************/
</script>
Example
VAPM,Almala Page 14
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
<script>
var x = Math.PI;
</script>
Method Description
Example
<script>
VAPM,Almala Page 15
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(a);
document.write("<br />");
a = Math.sqrt(64); //8
document.write(a);
document.write("<br />");
document.write(a);
document.write("<br />");
a = Math.log(20); //2.995732273553991
document.write(a);
document.write("<br />");
a = Math.exp(5); //148.41315910257657
document.write(a);
document.write("<br />");
a = Math.max(5,10); //10
VAPM,Almala Page 16
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(a);
document.write("<br />");
a = Math.min(5,10); //5
document.write(a);
document.write("<br />");
a = Math.min(-50,-49); //-50
document.write(a);
</script>
Method Description
VAPM,Almala Page 17
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Example
<script>
document.write(a);
document.write("<br />");
document.write(a);
document.write("<br />");
document.write(a);
</script>
Method Description
VAPM,Almala Page 18
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Example
<script>
document.write(a);
document.write("<br />");
a = Math.floor(12.4); //12
document.write(a);
document.write("<br />");
a = Math.round(12.4); //12
document.write(a);
document.write("<br />");
a = Math.round(12.5); //13
document.write(a);
</script>
VAPM,Almala Page 19
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Syntax
Precision factor represents the decimal level and is equal to 10 raise to the power of the decimal
places. For example if you want 2 decimal places, precision factor will be 100(10^2), for 3
decimal places it should be 1000(10^3).
Example
<script>
document.write(p);
document.write("<br />");
p = Math.round(p);
p /= 100;
document.write(p);
document.write("<br />");
VAPM,Almala Page 20
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(p);
</script>
Syntax
Math.random();
Example
<script>
var r = Math.random();
r *= 10;
document.write(r);
document.write("<br />");
VAPM,Almala Page 21
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(r);
</script>
Infinity in JavaScript
Infinity is a global property (variable) that is used to represent infinite values in JavaScript.
Example
<script>
var i = 100 / 0;
document.write(i); //Infinity
</script>
There are also two other global properties in JavaScript, POSITIVE_INFINITY and
NEGATIVE_INFINITY but they are rarely used.
NaN in JavaScript
NaN is a global property which means "Not a Number".
Example
<script>
document.write(n);
VAPM,Almala Page 22
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
</script>
String plays an important role in every programming languages. JavaScript is no exception. Also
every character in JavaScript is represented by some number. That numerical unicode is known
as charcode of that character. Example, 'A' is represented by 65.
Here are few functions that can be useful to help you out with your day to day coding work.
String Concatenation
String concatenation refers to combining one string to another. Simplest way to join strings is
using '+' (plus) operator. But there is also a method concat() which can be used to unite strings
together.
Syntax
//using + operator
Example
<script>
document.write(str);
VAPM,Almala Page 23
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write("<br />");
str = "JavaScript";
</script>
Splitting Strings
Various methods are available in JavaScript to get whole or some part of strings. Few commonly
used methods are as follows:
substring() method
substring method is used to get arbitrary string values between the index positions passed to it as
parameters.
Syntax
string.substring(start,[end])
First parameter specifies from where to copy the string. Second optional parameter specifies till
where to copy. Also, character specified by second parameter is not included. If second
parameter is not given then whole string after start position will be copied.
Example
<script>
VAPM,Almala Page 24
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(sub);
document.write("<br />)
str = 'JavaScript';
document.write(sub);
</script>
substr() method
substr method is somewhat similar to substring() method with just one difference. The second
parameter in the substr() method specifies the length of the string to be copied, not the end
position.
Syntax
string.substr(start,length)
Example
<script>
VAPM,Almala Page 25
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(sub);
document.write("<br />")
str = 'JavaScript';
document.write(sub);
</script>
slice() method
slice method is used to get characters from a string between specified indexes passed to it as
parameters.
Syntax
string.slice(start, [end])
The element at the 'end' index is not included. If end index is not specified then the result will be
from start index till the end of the string.
Example
<script>
VAPM,Almala Page 26
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(sub);
document.write("<br />");
document.write(sub);
</script>
split() method
split() method breaks a string into an array of string. It splits the string from the separator string
boundaries that is passed to it as parameter.
Syntax
string.split(separator,[size])
If no separator string is given then it will break the string into an array having just one element
which is string itself.
If optional size parameter is given then array formed will be of given size parameter ignoring the
rest of the characters.
Example
<script>
VAPM,Almala Page 27
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(sub); //JavaScript,is,fun
document.write("<br />");
document.write(sub); //JavaScript
document.write("<br />");
sub = str.split();
</script>
Changing Case
toLowerCase() method
toLowerCase() method is used to change the case of the string to lower case.
Syntax
string.toLowerCase()
Example
<script>
VAPM,Almala Page 28
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(lcase);
</script>
toUpperCase() method
toUpperCase() method is used to change the case of the string to upper case.
Syntax
string.toUpperCase()
Example
<script>
document.write(ucase);
</script>
Finding Characters
indexOf() method
indexOf() method is used to search for a given substring in the parent string and returns substring
position.
Syntax
VAPM,Almala Page 29
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
string.indexOf(needle,[fromIndex])
Optional second parameter decides from where to begin searching the string. It starts searching
from the beginning if optional second parameter is not given. In case needle(substring) is not
found then it returns -1.
Example
<script>
document.write(pos);
document.write("<br />");
document.write(pos);
</script>
lastIndexOf() method
lastIndexOf() method is used to search for a given substring beginning the search from the end. It
returns needle's position. In case needle(substring) is not found then it returns -1.
Syntax
string.lastIndexOf(needle,[fromIndex])
VAPM,Almala Page 30
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
It starts searching from the end if optional second parameter is not given. In case
needle(substring) is not found then it returns -1.
Example
<script>
document.write(pos);
document.write(pos);
</script>
search() method
search() returns the index position of the needle if found else it returns -1. It looks somewhat
similar to indexOf() method but seach() method works with regular expressions. Regular
expressions will be discussed later.
Syntax
string.search(regexp)
Example
<script>
VAPM,Almala Page 31
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(pos);
</script>
match() method
match() returns the substring(needle) if found in the main string else it returns null. match()
method also works with regular expressions. Performance wise indexOf() method is faster than
match() and search().
Syntax
string.match(regexp)
Example
<script>
document.write(pos);
</script>
charAt() method
VAPM,Almala Page 32
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
string.charAt(index)
Example
<script>
document.write(c);
</script>
charCodeAt() method
charCodeAt() returns the unicode numeric value of a character at a particular index which is
passed to it as an argument.
string.charAt(index)
Example
<script>
document.write(u);
VAPM,Almala Page 33
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
</script>
Syntax
string.replace(regular_expression/string, 'new_string')
Example
<script>
document.write(newStr);
</script>
Method Description
str.substring(start,[end]) returns substring from start to end unless end index position
VAPM,Almala Page 34
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
is specified
VAPM,Almala Page 35
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Date object in JavaScript can be used to get date and time. Date object has various methods to
exploit date and time. To get date and time use new keyword followed by with Date object
constructor.
Syntax
new Date();
Example
<script>
document.write(now);
document.write('<br />');
document.write(now);
VAPM,Almala Page 36
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
</script>
date.getDay() returns the day number (0-6, 0 for sun, 1 for mon and so on)
Example
<script>
var months = ['Jan', 'Feb', 'March', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
VAPM,Almala Page 37
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
day = days[day];
month = months[month];
document.write(day + " " + date + " " + month + " " + year);
</script>
VAPM,Almala Page 38
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Example
<script>
VAPM,Almala Page 39
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
</script>
String plays an important role in every programming languages. JavaScript is no exception. Also
every character in JavaScript is represented by some number. That numerical unicode is known
as charcode of that character. Example, 'A' is represented by 65.
Here are few functions that can be useful to help you out with your day to day coding work.
String Concatenation
String concatenation refers to combining one string to another. Simplest way to join strings is
using '+' (plus) operator. But there is also a method concat() which can be used to unite strings
together.
Syntax
//using + operator
Example
<script>
document.write(str);
document.write("<br />");
VAPM,Almala Page 40
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
str = "JavaScript";
</script>
Splitting Strings
Various methods are available in JavaScript to get whole or some part of strings. Few commonly
used methods are as follows:
substring() method
substring method is used to get arbitrary string values between the index positions passed to it as
parameters.
Syntax
string.substring(start,[end])
First parameter specifies from where to copy the string. Second optional parameter specifies till
where to copy. Also, character specified by second parameter is not included. If second
parameter is not given then whole string after start position will be copied.
Example
<script>
VAPM,Almala Page 41
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(sub);
document.write("<br />)
str = 'JavaScript';
document.write(sub);
</script>
substr() method
substr method is somewhat similar to substring() method with just one difference. The second
parameter in the substr() method specifies the length of the string to be copied, not the end
position.
Syntax
string.substr(start,length)
Example
<script>
VAPM,Almala Page 42
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(sub);
document.write("<br />")
str = 'JavaScript';
document.write(sub);
</script>
slice() method
slice method is used to get characters from a string between specified indexes passed to it as
parameters.
Syntax
string.slice(start, [end])
The element at the 'end' index is not included. If end index is not specified then the result will be
from start index till the end of the string.
Example
<script>
VAPM,Almala Page 43
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(sub);
document.write("<br />");
document.write(sub);
</script>
split() method
split() method breaks a string into an array of string. It splits the string from the separator string
boundaries that is passed to it as parameter.
Syntax
string.split(separator,[size])
If no separator string is given then it will break the string into an array having just one element
which is string itself.
If optional size parameter is given then array formed will be of given size parameter ignoring the
rest of the characters.
Example
<script>
document.write(sub); //JavaScript,is,fun
VAPM,Almala Page 44
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write("<br />");
document.write(sub); //JavaScript
document.write("<br />");
sub = str.split();
</script>
Changing Case
toLowerCase() method
toLowerCase() method is used to change the case of the string to lower case.
Syntax
string.toLowerCase()
Example
<script>
document.write(lcase);
VAPM,Almala Page 45
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
</script>
toUpperCase() method
toUpperCase() method is used to change the case of the string to upper case.
Syntax
string.toUpperCase()
Example
<script>
document.write(ucase);
</script>
Finding Characters
indexOf() method
indexOf() method is used to search for a given substring in the parent string and returns substring
position.
Syntax
string.indexOf(needle,[fromIndex])
VAPM,Almala Page 46
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Optional second parameter decides from where to begin searching the string. It starts searching
from the beginning if optional second parameter is not given. In case needle(substring) is not
found then it returns -1.
Example
<script>
document.write(pos);
document.write("<br />");
document.write(pos);
</script>
lastIndexOf() method
lastIndexOf() method is used to search for a given substring beginning the search from the end. It
returns needle's position. In case needle(substring) is not found then it returns -1.
Syntax
string.lastIndexOf(needle,[fromIndex])
It starts searching from the end if optional second parameter is not given. In case
needle(substring) is not found then it returns -1.
Example
VAPM,Almala Page 47
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
<script>
document.write(pos);
document.write(pos);
</script>
search() method
search() returns the index position of the needle if found else it returns -1. It looks somewhat
similar to indexOf() method but seach() method works with regular expressions. Regular
expressions will be discussed later.
Syntax
string.search(regexp)
Example
<script>
VAPM,Almala Page 48
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(pos);
</script>
match() method
match() returns the substring(needle) if found in the main string else it returns null. match()
method also works with regular expressions. Performance wise indexOf() method is faster than
match() and search().
Syntax
string.match(regexp)
Example
<script>
document.write(pos);
</script>
charAt() method
charAt() returns the character at a particular index which is passed to it as an argument.
string.charAt(index)
VAPM,Almala Page 49
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Example
<script>
document.write(c);
</script>
charCodeAt() method
charCodeAt() returns the unicode numeric value of a character at a particular index which is
passed to it as an argument.
string.charAt(index)
Example
<script>
document.write(u);
</script>
replace() method
replace() method is used to find and replace some or all occurrence of a string/character with
some new specified string/character within a string. To replace more than one value within a
string pass regular expression as first argument.
Syntax
string.replace(regular_expression/string, 'new_string')
Example
<script>
document.write(newStr);
</script>
Method Description
VAPM,Almala Page 51
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
1. If statement
2. If…Else statement
3. If…Else If…Else statement
VAPM,Almala Page 52
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
If statement
Syntax:
if (condition)
You can use If statement if you want to check only a specific condition.
<html>
<head>
<title>IF Statments!!!</title>
<script type="text/javascript">
if(age>=18)
if(age<18)
</script>
VAPM,Almala Page 53
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
</head>
<body>
</body>
</html>
VAPM,Almala Page 54
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
What is JavaScript?
JavaScript is a scripting language that is created for showing HTML pages live. JavaScript does
not require any compilation. It is interpreted language. JavaScript can modify HTML page, write
text in it, add or remove tags, change styles etc.
JavaScript code can get to execute on events, mouse clicks, and movements, keyboard input etc.
It can send the request to the server and load data without reloading of the page. This technology
is often called “AJAX”. JavaScript makes the web pages dynamic.
Advantages of JavaScript
Adding new HTML to the page, change the existing content, modify styles.
React to the user actions, run on mouse clicks, pointer movements, key presses.
Send requests through the network to remote servers, download and upload files. It is called
AJAX and COMET Technologies.
In this JavaScript tutorial, we will learn different JavaScript Features and how we inculcate it
in writing HTML pages. It gives insight about how modern features of JavaScript are widely
used.
We will discuss different unique features of JavaScript and various features of Modern
JavaScript with examples.
2. Greater Control
Example – You can change the background color of the page as well as text on the browser’s
status bar.
Here, the back button is implemented with JavaScript. Click it and you will return to the page
from which you have arrived.
The feature to detect the user’s browser and OS enables your script to perform platform–
dependent operations.
VAPM,Almala Page 1
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
In the JavaScript calculator, try to type some letters instead of numeric input, you will get an
error: Invalid input character. Note that, JavaScript helps the browser perform output validation
without wasting the user’s time by the web server access.
If the user makes a mistake in the input, the user will get an error message immediately. If the
input information is validated only on the server, then the user would have to wait for the
server’s response.
The JavaScript says, “Nice Morning, isn’t it? Or “Good Afternoon”, depending on the current
time. It also tells you today’s date.
Every time you click on the button, the browser generates and displays a new HTML code.
Thanks to JavaScript, this operation performs on the client- machine and therefore you don’t
have to wait while the information backs and forth between your browser and the web server.
8. Semicolon Insertion
All statements in JavaScript must terminate with a semicolon. Most of the JavaScript control
statements syntax is the same as control statements in C.
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For example:
car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is template based not class based. Here, we don't create class to get the object. But, we
direct create objects.
1. By object literal
VAPM,Almala Page 2
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
1. object={property1:value1,property2:value2.....propertyN:valueN}
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Here, you need to create function with arguments. Each argument value can be assigned in the
current object by using this keyword.
VAPM,Almala Page 3
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
We can define method in JavaScript object. But before defining method, we need to add property
in the function with same name as method.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>
VAPM,Almala Page 4
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
VAPM,Almala Page 5
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
VAPM,Almala Page 6
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Conditional Operator (Ternary Operator)
6. Bitwise Operators
7. Miscellaneous Operators
1. typeof
2. delete
3. instanceof
4. new
5. this
6. in
We are use in our routine life arithmetic operators, addition(+), subtraction(-), multiplication (*),
and division (/) and some other arithmetic operator are listed below.
VAPM,Almala Page 7
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
<script>
var x = 10, y = 5;
document.writeln(x + y); // Addition: 15
document.writeln(x - y); // Subtraction: 5
document.writeln(x * y); // Multiplication: 50
document.writeln(x / y); // Division: 2
document.writeln(x % y); // Modulus: 0
VAPM,Almala Page 8
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
JavaScript assignment operators assign values to left operand based on right operand. equal (=)
operators is used to assign a values.
Addition += Addition of operands and finally assign result += result = result result =
to left operand. x +y 22
Division /= Division of operands and finally assign result /= result = result / result =
to left operand. y y 17
Modulus %= Modulus of operands and finally assign result %= result = result result =
to left operand. y %y 2
Bitwise AND &= AND operator compare two bits values result &= result = result result =
return a results of 1, If both bits are 1. y &y 0
otherwise return 0. =2&5
= 0000 0010 &
0000 0101
= 0000 0000 =
0
Bitwise OR |= OR operator compare two bits values result |= y result = result | result =
and return result of 1, If the bits are y 7
complementary. Otherwise return 0. =2|5
= 0000 0010 |
0000 0101
= 0000 0111 =
VAPM,Almala Page 9
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Shift Left <<= Shift left operator move the bits to a result result = result result =
left side. <<= y <<= y 64
= 2 <<= 5
= 0000 0010
<<= 0100
0000
= 64
Shift Right >>= Shift left operator move the bits to a result result = result result =
left side. >>= y >>= y 2
= 2 >>= 5
= 0100 0000
>>= 0000
0010
=2
<script>
var x = 17, y = 5;
var result = x; // Assignment to left operand(result) base on right operand(y).
document.writeln(result);
document.writeln(result += x);
document.writeln(result -= y);
document.writeln(result *= y);
document.writeln(result /= y);
document.writeln(result %= y);
VAPM,Almala Page 10
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Identical equal === If both operands are equal and/or same data type, returns true.
Identical not equal !== If both operands are not equal and/or same data type, returns true.
Greater than > If left operand larger than right operand, return true.
Less then < If left operand smaller than right operand, return true.
Greater than, equal >= If left operand larger or equal than right operand, return true.
Less than, equal <= If left operand smaller or equal than right operand, return true.
<script>
document.writeln(5 == 5); // true
document.writeln(5 == '5'); // true
VAPM,Almala Page 11
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Logical AND && If first operand evaluate and return a true, only that evaluate the second
operand otherwise skips.
Return true if both are must be true, otherwise return false.
Logical NOT ! Return the inverse of the given value result true become false, and false
become true.
<script>
document.writeln((5 == 5) && (10 == 10)); // true
document.writeln(true && false); // false
VAPM,Almala Page 12
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Example
document.write((10 == 10) ? "Same value" : "different value");
Run it... »
Bitwise AND & Return bitwise AND operation for given two operands.
Bitwise XOR ^ Return bitwise XOR operation for given two operands.
VAPM,Almala Page 13
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Bitwise Unsigned Shift >>> Return right shift without consider sign of given operands.
Right
<script>
document.writeln(5 & 10); // return 0, calculation: 0000 0101 & 0000 1010 = 0000 0000
document.writeln(5 | 10); // return 15, calculation: 0000 0101 | 0000 1010 = 0000 1111
document.writeln(5 ^ 10); // return 15, calculation: 0000 0101 ^ 0000 1010 = 0000 1111
document.writeln(~5); // return -6, calculation: ~ 0000 0101 = 1111 1010
document.writeln(10 << 2); // return 40, calculation: 0000 1010 << 2 = 0010 1000
document.writeln(10 >> 2); // return 2, calculation: 0000 1010 >> 2 = 0000 0010
document.writeln(10 >>> 2); // return 2, calculation: 0000 1010 >>> 2 = 0000 0010
</script>
Run it... »
Miscellaneous Operators
1. typeof
2. delete
3. instanceof
4. new
5. this
6. in
typeof
JavaScript typeof operator return valid data type identifiers as a string of given
expression. typeof operator return six possible
values: "string", "number", "boolean", "object", "function", and "undefined".
typeof expression
typeof(expression)
Example
VAPM,Almala Page 14
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
delete
JavaScript delete operator deletes object property or remove specific element in array.
If delete is not allow (you can't delete if element not exist, array element undefined etc..) then
return false otherwise return true.
delete expression; // delete explicit declare variable
Example
var address = "63 street Ct.";
delete address; // Returns false, Using var keyword you can't delete
add = "63 street Ct.";
delete add; // Returns true, explicit declare you can delete
VAPM,Almala Page 15
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
instanceof
JavaScript instanceof indicate boolean result, Return true, If object is an instance of specific
class.
object instanceof class
Example
<script>
var num1 = new Number(15);
document.writeln(num1 instanceof Number); // Returns true
var num2 = 10;
document.writeln(num2 instanceof Number); // Return false
VAPM,Almala Page 16
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
</script>
Run it... »
new
JavaScript new operator to create an instance of the object.
var myObj = new Object;
var myObj = new Object( ); // or you can write
// Object - required, for constructor of the object.
Example
var myObj = new Object(); // or you can write: var myObj = new Object;
myObj.name = "Opal Kole";
myObj.address = "63 street Ct.";
myObj.age = 48;
myObj.married = true;
console.log(myObj);
// Object {name: "Opal Kole", address: "63 street Ct.", age: 48, married: true}
Run it... »
this
JavaScript this operator represent current object.
this["propertyname"]
this.propertyname
Example
function employee(name, address, age, married) {
this.name = name;
this.address = address;
this.age = age;
this.married = married;
VAPM,Almala Page 17
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
}
var myObj = new employee("Opal Kole", "63 street Ct.", 48, true);
console.log(myObj);
// employee {name: "Opal Kole", address: "63 street Ct.", age: 48, married: true}
Run it... »
in
JavaScript in operator return boolean result if specified property exist in object.
property in object
Example
<script>
var myObj = new Object(); // or you can write: var myObj = new Object;
myObj.name = "Opal Kole";
myObj.address = "63 street Ct.";
myObj.age = 48;
myObj.married = true;
if statement
if is used to check for a condition whether its true or not. Condition could be any expression that
returns true or false. When condition satisfies then statements following if statement are
executed.
Syntax
if(condition)
VAPM,Almala Page 18
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
statement1
statement2
...
If you have only one statement to be executed after the if condition then you can drop the curly
braces ({ }). For more than one statement use curly braces.
if(condition)
statement
But still its good practice to use curly braces. It will help to easily manage and understand your
code.
Example
<script>
if(5>4)
document.write("<br />");
/********outputs*********
VAPM,Almala Page 19
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
JavaScript is fun
************************/
if(true)
/********outputs*********
************************/
if(1===3)
</script>
else statement
else statements are used with if statements. When if condition gets fail then else statement is
executed.
Syntax
if(condition)
VAPM,Almala Page 20
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
statements
else
statements
You can drop off the curly braces with else too if there is a single statement to be executed
within else.
Example
<script>
if(3>4)
document.write("True");
else
document.write("False");
//outputs False
VAPM,Almala Page 21
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
</script>
else if statement
Suppose there are variety of conditions that you want to check. You can use multiple if
statements to do this task. All the if conditions will be checked one by one. But what if you want
that if one condition satisfies then don't perform further conditional checks. At this point else
if statement is what you need.
Syntax
if(condition)
statements
else if(condition)
statements
else
statements
Example
<script>
VAPM,Almala Page 22
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
var a=3;
var b=4;
if(a > b)
else
document.write("Nothing worked");
</script>
switch statement
switch statements do the same task that else if statements do. But use switch statements when
conditions are more. In that case, switch statements perform better than else if statements.
Syntax
switch(expression)
VAPM,Almala Page 23
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
............
switch evaluates the expression and checks whether it matches with any case. If it matches with
any case then statements within that case construct are executed followed by break statement.
break statement makes sure that no more case statement gets executed. In case if the expression
doesn't match any case value then default case is executed.
There could be any number of statements. No curly braces is needed inside case construct. Also
you can omit the break statement in the default construct if default is the last statement within
switch.
Example
<script>
var a = 7;
VAPM,Almala Page 24
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
switch(a)
//outputs three
</script>
Note: Check that I have dropped the break statement for the default case construct. It will work
fine but try to put the default statement above case 1 and see the result. Also try this program
removing all the break statements.
case value can be any number, character or string. Keep this in mind.
Example
<script>
var i = 'h';
switch(i)
VAPM,Almala Page 25
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
//outputs h found
</script>
Syntax
If condition goes right then statement before colon is executed and if false then statement after
colon is executed. Multiple statements are not allowed. But you can execute multiple statements
by making a function and calling the function if the condition goes true or false accordingly.
Example
<script>
document.write("<br />");
VAPM,Almala Page 26
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write("<br />");
//outputs False
var a = (true) ? 1 : 2;
document.write(a);
//outputs 1
</script>
Syntax
if(condition)
if(other condition)
statements;
VAPM,Almala Page 27
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
else
if(other condition)
statements;
else
switch(expression)
......
Converting a data type into another is known as type casting. Sometimes there is a need to
convert the data type of one value to another.
typeof
typeof operator is used to return the data type of an operand.
Syntax
VAPM,Almala Page 28
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
typeof operand;
Example
<script>
var a;
document.write("<br />");
document.write("<br />");
document.write("<br />");
document.write("<br />");
document.write("<br />");
VAPM,Almala Page 29
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write("<br />");
</script>
The code is self explanatory. The variable a has not been initialized that's why its type is
showing as undefined. Try to assign some value to it and see the result.
Converting to Boolean
To convert a value to boolean data type, just pass the value to Boolean function.
Syntax
Boolean(value);
Example
<script>
var b = 1;
b = Boolean(b);
</script>
Converting to String
To convert a value to string data type, just pass the value to String function.
Syntax
VAPM,Almala Page 30
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
String(value);
Example
<script>
var s = 1;
s= String(s);
</script>
Converting to Number
Many times string needs to get converted into numbers. To convert a value to number data type,
just pass the value to Number function.
Syntax
Number(value);
Example
<script>
var n1 = true;
var n2 = "1str";
VAPM,Almala Page 31
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
var n3 = "123";
n1 = Number(n1);
n2 = Number(n2);
n3 = Number(n3);
document.write("<br />");
document.write("<br />");
document.write("<br />");
</script>
parseInt
parseInt() function is used to convert strings values into numbers. It works differently than
Number() function. It doesn't work for boolean or other data-types values. For others values or
VAPM,Almala Page 32
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
string that doen't contain numbers in it, parseInt() will just output NaN. Examples will clear this
idea.
Syntax
parseInt(string);
Example
<script>
var n1 = true;
var n2 = "1str";
var n3 = "123";
var n4 = "str123str1";
n1 = parseInt(n1);
n2 = parseInt(n2);
n3 = parseInt(n3);
n4 = parseInt(n4);
document.write("<br />");
document.write("<br />");
VAPM,Almala Page 33
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write("<br />");
document.write("<br />");
</script>
parseFloat
parseFloat() function is used to convert strings values into floating point numbers. It works
similar to parseInt() function with an exception of handling decimal point numbers. For example,
1.23 is represented as 123e-2. parseInt("123e-2") will result in 123 but parseFloat("123e-2") will
give 1.23.
Syntax
parseFloat(string);
Example
<script>
var n1 = "123e-2";
var n2 = "1str";
var n3 = "123";
var n4 = "str123str1";
VAPM,Almala Page 34
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
n1 = parseFloat(n1);
n2 = parseFloat(n2);
n3 = parseFloat(n3);
n4 = parseFloat(n4);
document.write("<br />");
document.write("<br />");
document.write("<br />");
document.write("<br />");
</script>
Loops in JavaScript
Loops are used to execute a specific statement for a given number of times. Loops are always
followed by some condition. JavaScript provides all the basic loops that other programming
languages have.
VAPM,Almala Page 35
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
while loop
while loop checks for a given condition to be true to execute statements that it contains within it.
When the condition becomes false, while loop break the execution of statements.
Syntax
initializer;
while(condition)
statement-1;
statement-2;
.....
modifier;
initializer is a variable that is tested within the condition. modifier modifies the initializer so that
the condition becomes false at some point.
Note: Make sure that your condition goes false somehow else you will be in an infinite loop.
Example
<script>
var i = 0;
while(i<6)
document.write(i);
document.write("<br />");
i++;
VAPM,Almala Page 36
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
</script>
do while loop
do while loop first execute the statements that it contain and then check for a condition. So even
if the condition is false do-while loop is going to run at least once.
Syntax
initializer;
do
statement-1;
statement-2;
.....
modifier;
while(condition);
Example
<script>
var i = 5;
do
VAPM,Almala Page 37
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(i);
document.write("<br />");
i++;
while(i<6);
</script>
for loop
for loop is generally used when the number of iterations/repetitions are already known. Its not
that such tasks can't be done by while loop but its just a matter of preference.
Syntax
statement-1;
.....
Here, initializer is a variable that is defined once in the beginning of a for loop. It is optional and can be
ignored. condition is checked after initialization. Then statements are executed and finally modifier
modifies the initializer. After that again condition is checked and the process continues. Modifier can also
be ignored.
You can drop the curly braces if only one statement is within the for loop.
Syntax
VAPM,Almala Page 38
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
<script>
for(var i=0;i<10;i++)
document.write(i);
document.write("<br />");
</script>
Nested Loops
Any loop can be inserted inside any other loop. This is called nesting. for loop can be nested
inside while or for loop. Similarly while loop can be nested inside for loop or another while loop.
Syntax
while(condition)
statements;
Example
<script>
VAPM,Almala Page 39
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
var i,j;
for(i=0;i<3;i++)
document.write("<br />");
for(j=0;j<3;j++)
document.write("<br />");
document.write("<br />");
/*************output***************
Outer Loop : 0
Inner Loop : 0
Inner Loop : 1
Inner Loop : 2
VAPM,Almala Page 40
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Outer Loop : 1
Inner Loop : 0
Inner Loop : 1
Inner Loop : 2
Outer Loop : 2
Inner Loop : 0
Inner Loop : 1
Inner Loop : 2
***********************************/
</script>
Can you guess how above loop works? First outer for loop initializes i, checks for the condition
then executes its first two statements. After that inner for loop starts to work. After executing its
statements 3 times, outer for loop is given the control again. And the process is repeated.
Loop control statements deviates a loop from its normal flow. All the loop control statements are
attached to some condition inside the loop.
break statement
break statement is used to break the loop on some condition.
Syntax
if(condition)
VAPM,Almala Page 41
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
break;
statements;
while(condition)
if(condition)
break;
statements;
Example
<script>
for(var i=1;i<10;i++)
if(i===7) break;
VAPM,Almala Page 42
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
/**********output***********
***************************/
</script>
for loop should print from 1 - 10. But inside loop we have given a condition that if value of i
equals to 7, then break out of loop. I have left the curly braces within the if condition because
there is only one statement to be executed.
Remember break burst the nearest for loop within which it is contained. To understand what
it means check out the next example.
Example
<script>
for(var i=1;i<=3;i++)
VAPM,Almala Page 43
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
for(var j=1;j<=3;j++)
if(j===2)
break;
document.write("<br />");
/**********output***********
Outer Loop : 1
Inner Loop : 1
Inner Loop : 2
Outer Loop : 2
Inner Loop : 1
Inner Loop : 2
VAPM,Almala Page 44
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Outer Loop : 3
Inner Loop : 1
Inner Loop : 2
***************************/
</script>
continue statement
continue statement is used to skip an iteration of a loop.
Syntax
if(condition)
continue;
statements;
while(condition)
if(condition)
VAPM,Almala Page 45
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
continue;
statements;
Example
<script>
for(var i=0;i<10;i++)
/**********output***********
VAPM,Almala Page 46
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
***************************/
</script>
In the code above when the value of i becomes 3 or 7, continue forces the loop to skip without
further executing any instructions inside the for loop in that current iteration.
Remember continue skips the nearest loop iteration within which it is contained. To
understand what it means check out the next example.
Example
<script>
for(var i=1;i<=3;i++)
for(var j=1;j<=3;j++)
if(j===2)
continue;
VAPM,Almala Page 47
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write("<br />");
/**********output***********
Outer Loop : 1
Inner Loop : 1
Inner Loop : 3
Outer Loop : 2
Inner Loop : 1
Inner Loop : 3
Outer Loop : 3
Inner Loop : 1
Inner Loop : 3
***************************/
</script>
VAPM,Almala Page 48
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Example
<script>
var x = Math.PI;
</script>
VAPM,Almala Page 49
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Method Description
Example
<script>
document.write(a);
document.write("<br />");
a = Math.sqrt(64); //8
document.write(a);
document.write("<br />");
VAPM,Almala Page 50
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(a);
document.write("<br />");
a = Math.log(20); //2.995732273553991
document.write(a);
document.write("<br />");
a = Math.exp(5); //148.41315910257657
document.write(a);
document.write("<br />");
a = Math.max(5,10); //10
document.write(a);
document.write("<br />");
a = Math.min(5,10); //5
document.write(a);
document.write("<br />");
a = Math.min(-50,-49); //-50
VAPM,Almala Page 51
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(a);
</script>
Method Description
Example
<script>
document.write(a);
document.write("<br />");
VAPM,Almala Page 52
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(a);
document.write("<br />");
document.write(a);
</script>
Method Description
Example
<script>
document.write(a);
document.write("<br />");
VAPM,Almala Page 53
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
a = Math.floor(12.4); //12
document.write(a);
document.write("<br />");
a = Math.round(12.4); //12
document.write(a);
document.write("<br />");
a = Math.round(12.5); //13
document.write(a);
</script>
Syntax
Precision factor represents the decimal level and is equal to 10 raise to the power of the decimal
places. For example if you want 2 decimal places, precision factor will be 100(10^2), for 3
decimal places it should be 1000(10^3).
VAPM,Almala Page 54
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Example
<script>
document.write(p);
document.write("<br />");
p = Math.round(p);
p /= 100;
document.write(p);
document.write("<br />");
document.write(p);
</script>
VAPM,Almala Page 55
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
with 10 will increase its range from 0.0 to 10.0. And to get an integer range, use Math.ceil() so
that the range actually becomes 1 to 10. You can use Math.floor() to make the range between 0
and 9.
Syntax
Math.random();
Example
<script>
var r = Math.random();
r *= 10;
document.write(r);
document.write("<br />");
document.write(r);
</script>
Infinity in JavaScript
Infinity is a global property (variable) that is used to represent infinite values in JavaScript.
Example
<script>
VAPM,Almala Page 56
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
var i = 100 / 0;
document.write(i); //Infinity
</script>
There are also two other global properties in JavaScript, POSITIVE_INFINITY and
NEGATIVE_INFINITY but they are rarely used.
NaN in JavaScript
NaN is a global property which means "Not a Number".
Example
<script>
document.write(n);
</script>
String plays an important role in every programming languages. JavaScript is no exception. Also
every character in JavaScript is represented by some number. That numerical unicode is known
as charcode of that character. Example, 'A' is represented by 65.
Here are few functions that can be useful to help you out with your day to day coding work.
String Concatenation
VAPM,Almala Page 57
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
String concatenation refers to combining one string to another. Simplest way to join strings is
using '+' (plus) operator. But there is also a method concat() which can be used to unite strings
together.
Syntax
//using + operator
Example
<script>
document.write(str);
document.write("<br />");
str = "JavaScript";
VAPM,Almala Page 58
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
</script>
Splitting Strings
Various methods are available in JavaScript to get whole or some part of strings. Few commonly
used methods are as follows:
substring() method
substring method is used to get arbitrary string values between the index positions passed to it as
parameters.
Syntax
string.substring(start,[end])
First parameter specifies from where to copy the string. Second optional parameter specifies till
where to copy. Also, character specified by second parameter is not included. If second
parameter is not given then whole string after start position will be copied.
Example
<script>
document.write(sub);
document.write("<br />)
str = 'JavaScript';
VAPM,Almala Page 59
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(sub);
</script>
substr() method
substr method is somewhat similar to substring() method with just one difference. The second
parameter in the substr() method specifies the length of the string to be copied, not the end
position.
Syntax
string.substr(start,length)
Example
<script>
document.write(sub);
document.write("<br />")
str = 'JavaScript';
VAPM,Almala Page 60
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(sub);
</script>
slice() method
slice method is used to get characters from a string between specified indexes passed to it as
parameters.
Syntax
string.slice(start, [end])
The element at the 'end' index is not included. If end index is not specified then the result will be
from start index till the end of the string.
Example
<script>
document.write(sub);
document.write("<br />");
document.write(sub);
VAPM,Almala Page 61
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
</script>
split() method
split() method breaks a string into an array of string. It splits the string from the separator string
boundaries that is passed to it as parameter.
Syntax
string.split(separator,[size])
If no separator string is given then it will break the string into an array having just one element
which is string itself.
If optional size parameter is given then array formed will be of given size parameter ignoring the
rest of the characters.
Example
<script>
document.write(sub); //JavaScript,is,fun
document.write("<br />");
document.write(sub); //JavaScript
document.write("<br />");
VAPM,Almala Page 62
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
sub = str.split();
</script>
Changing Case
toLowerCase() method
toLowerCase() method is used to change the case of the string to lower case.
Syntax
string.toLowerCase()
Example
<script>
document.write(lcase);
</script>
toUpperCase() method
toUpperCase() method is used to change the case of the string to upper case.
Syntax
VAPM,Almala Page 63
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
string.toUpperCase()
Example
<script>
document.write(ucase);
</script>
Finding Characters
indexOf() method
indexOf() method is used to search for a given substring in the parent string and returns substring
position.
Syntax
string.indexOf(needle,[fromIndex])
Optional second parameter decides from where to begin searching the string. It starts searching
from the beginning if optional second parameter is not given. In case needle(substring) is not
found then it returns -1.
Example
<script>
VAPM,Almala Page 64
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(pos);
document.write("<br />");
document.write(pos);
</script>
lastIndexOf() method
lastIndexOf() method is used to search for a given substring beginning the search from the end. It
returns needle's position. In case needle(substring) is not found then it returns -1.
Syntax
string.lastIndexOf(needle,[fromIndex])
It starts searching from the end if optional second parameter is not given. In case
needle(substring) is not found then it returns -1.
Example
<script>
document.write(pos);
VAPM,Almala Page 65
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(pos);
</script>
search() method
search() returns the index position of the needle if found else it returns -1. It looks somewhat
similar to indexOf() method but seach() method works with regular expressions. Regular
expressions will be discussed later.
Syntax
string.search(regexp)
Example
<script>
document.write(pos);
</script>
match() method
VAPM,Almala Page 66
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
match() returns the substring(needle) if found in the main string else it returns null. match()
method also works with regular expressions. Performance wise indexOf() method is faster than
match() and search().
Syntax
string.match(regexp)
Example
<script>
document.write(pos);
</script>
charAt() method
charAt() returns the character at a particular index which is passed to it as an argument.
string.charAt(index)
Example
<script>
VAPM,Almala Page 67
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(c);
</script>
charCodeAt() method
charCodeAt() returns the unicode numeric value of a character at a particular index which is
passed to it as an argument.
string.charAt(index)
Example
<script>
document.write(u);
</script>
Syntax
VAPM,Almala Page 68
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
string.replace(regular_expression/string, 'new_string')
Example
<script>
document.write(newStr);
</script>
Method Description
VAPM,Almala Page 69
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Date object in JavaScript can be used to get date and time. Date object has various methods to
exploit date and time. To get date and time use new keyword followed by with Date object
constructor.
Syntax
new Date();
VAPM,Almala Page 70
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Example
<script>
document.write(now);
document.write('<br />');
document.write(now);
</script>
date.getDay() returns the day number (0-6, 0 for sun, 1 for mon and so on)
VAPM,Almala Page 71
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
Example
<script>
var months = ['Jan', 'Feb', 'March', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
day = days[day];
VAPM,Almala Page 72
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
month = months[month];
document.write(day + " " + date + " " + month + " " + year);
</script>
Example
VAPM,Almala Page 73
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
<script>
</script>
String plays an important role in every programming languages. JavaScript is no exception. Also
every character in JavaScript is represented by some number. That numerical unicode is known
as charcode of that character. Example, 'A' is represented by 65.
Here are few functions that can be useful to help you out with your day to day coding work.
String Concatenation
VAPM,Almala Page 74
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
String concatenation refers to combining one string to another. Simplest way to join strings is
using '+' (plus) operator. But there is also a method concat() which can be used to unite strings
together.
Syntax
//using + operator
Example
<script>
document.write(str);
document.write("<br />");
str = "JavaScript";
VAPM,Almala Page 75
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
</script>
Splitting Strings
Various methods are available in JavaScript to get whole or some part of strings. Few commonly
used methods are as follows:
substring() method
substring method is used to get arbitrary string values between the index positions passed to it as
parameters.
Syntax
string.substring(start,[end])
First parameter specifies from where to copy the string. Second optional parameter specifies till
where to copy. Also, character specified by second parameter is not included. If second
parameter is not given then whole string after start position will be copied.
Example
<script>
document.write(sub);
document.write("<br />)
str = 'JavaScript';
VAPM,Almala Page 76
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(sub);
</script>
substr() method
substr method is somewhat similar to substring() method with just one difference. The second
parameter in the substr() method specifies the length of the string to be copied, not the end
position.
Syntax
string.substr(start,length)
Example
<script>
document.write(sub);
document.write("<br />")
str = 'JavaScript';
VAPM,Almala Page 77
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(sub);
</script>
slice() method
slice method is used to get characters from a string between specified indexes passed to it as
parameters.
Syntax
string.slice(start, [end])
The element at the 'end' index is not included. If end index is not specified then the result will be
from start index till the end of the string.
Example
<script>
document.write(sub);
document.write("<br />");
document.write(sub);
VAPM,Almala Page 78
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
</script>
split() method
split() method breaks a string into an array of string. It splits the string from the separator string
boundaries that is passed to it as parameter.
Syntax
string.split(separator,[size])
If no separator string is given then it will break the string into an array having just one element
which is string itself.
If optional size parameter is given then array formed will be of given size parameter ignoring the
rest of the characters.
Example
<script>
document.write(sub); //JavaScript,is,fun
document.write("<br />");
document.write(sub); //JavaScript
document.write("<br />");
VAPM,Almala Page 79
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
sub = str.split();
</script>
Changing Case
toLowerCase() method
toLowerCase() method is used to change the case of the string to lower case.
Syntax
string.toLowerCase()
Example
<script>
document.write(lcase);
</script>
toUpperCase() method
toUpperCase() method is used to change the case of the string to upper case.
Syntax
VAPM,Almala Page 80
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
string.toUpperCase()
Example
<script>
document.write(ucase);
</script>
Finding Characters
indexOf() method
indexOf() method is used to search for a given substring in the parent string and returns substring
position.
Syntax
string.indexOf(needle,[fromIndex])
Optional second parameter decides from where to begin searching the string. It starts searching
from the beginning if optional second parameter is not given. In case needle(substring) is not
found then it returns -1.
Example
<script>
VAPM,Almala Page 81
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(pos);
document.write("<br />");
document.write(pos);
</script>
lastIndexOf() method
lastIndexOf() method is used to search for a given substring beginning the search from the end. It
returns needle's position. In case needle(substring) is not found then it returns -1.
Syntax
string.lastIndexOf(needle,[fromIndex])
It starts searching from the end if optional second parameter is not given. In case
needle(substring) is not found then it returns -1.
Example
<script>
document.write(pos);
VAPM,Almala Page 82
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(pos);
</script>
search() method
search() returns the index position of the needle if found else it returns -1. It looks somewhat
similar to indexOf() method but seach() method works with regular expressions. Regular
expressions will be discussed later.
Syntax
string.search(regexp)
Example
<script>
document.write(pos);
</script>
match() method
VAPM,Almala Page 83
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
match() returns the substring(needle) if found in the main string else it returns null. match()
method also works with regular expressions. Performance wise indexOf() method is faster than
match() and search().
Syntax
string.match(regexp)
Example
<script>
document.write(pos);
</script>
charAt() method
charAt() returns the character at a particular index which is passed to it as an argument.
string.charAt(index)
Example
<script>
VAPM,Almala Page 84
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
document.write(c);
</script>
charCodeAt() method
charCodeAt() returns the unicode numeric value of a character at a particular index which is
passed to it as an argument.
string.charAt(index)
Example
<script>
document.write(u);
</script>
Syntax
VAPM,Almala Page 85
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
string.replace(regular_expression/string, 'new_string')
Example
<script>
document.write(newStr);
</script>
Method Description
VAPM,Almala Page 86
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
1. If statement
2. If…Else statement
3. If…Else If…Else statement
If statement
Syntax:
if (condition)
VAPM,Almala Page 87
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
You can use If statement if you want to check only a specific condition.
<html>
<head>
<title>IF Statments!!!</title>
<script type="text/javascript">
if(age>=18)
if(age<18)
</script>
</head>
<body>
</body>
VAPM,Almala Page 88
CSS[22519] MR.SWAMI R.S.[MOBILE NO :-+91-8275265361]
</html>
VAPM,Almala Page 89
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Introduction
JavaScript Cookies are a great way to save a user's preferences in his / her browser. This is useful
for websites and users both, if not used to steal privacy.
A cookie is a small piece of text stored on the visitor's computer by a web browser. As the
information is stored on the hard drive it can be accessed later, even after the computer is turned
off.
A cookie can be used for authenticating, session tracking, remember specific information about
the user like his name, password, last visited date etc.
As cookies as a simple piece of text they are not executable. In javaScript, we can create and
retrieve cookie data with JavaScript's document object's cookie property.
The first is that all modern browser support cookies, but the user can disable them. In IE,
go to Tools and select Internet options, a window will come. Click on privacy and select
advanced button, another new window will come, from here you can disable cookie.
Cookies can identify the computer being used, not the individual.
The most modern browser is expected to be able to store at least 300 cookies of four
kilobytes (4 kb) per server or domain.
For each domain and path, you can store upto 20 cookies.
Cookies cannot access by any other computer except the visitor's computer that created
the cookie.
A website can set and read only its own cookies (for example, Yahoo can’t read IE's
cookies).
cookies.txt :
During the browsing session browser stores the cookies in memory, at the time of quitting they
goto the file called cookies.txt. Different browser store cookies files in a different location in the
disk.
For example on windows 2000 firefox stores the cookies into C:\Documents and
Settings\your_login_name_here\LocalSettings\ApplicationData\Mozilla\Firefox\Profiles\default
.7g1\Cache. Note that the "default.7g1" folder name may vary depending on the version of
Firefox you have Everytime When you open your browser, your cookies are read from the stored
location and at the closing, your browser, cookies are reserved to disk. As a cookie expires it is
no longer saved to the hard drive.
There are six parts of a cookie : name, value, expires, path, domain, and security. The first two
parts i.e. name and value are required and rest parts are optional.
Syntax
The first part of the cookie string must have the name and value. The entire name/value must be
a single string with no commas, semicolons or whitespace characters. Here is an example which
stores the string "George" to a cookie named 'myName". The JavaScript statement is :
document.cookie = "myName=George";
Using encodeURIComponent() function it is ensured that the cookie value string does not
contain any commas, semicolons, or whitespace characters. which are not allowed in cookie
values.
encodeURIComponent("Good Morning");
[VAPM,Almala-Inst.Code-1095
]2 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Good%20Morning
Good Morning.
expires
The cookie has a very limited lifespan. It will disappear when a user exits the browser. To give
more life to the cookies you must set an expiration date in the following format.
Here is an example where the cookie will live upto Mon, 12 Jun 2011:00:00:00 GMT
In the above example we have written the date in the pages, but in real life, you can use the Date
object to get the current date, and then set a cookie to expire six months or ten months.
cookieExpire.setMonth(cookieExpire.getMonth() + 10);
Copy
The above JavaScript code will create a new cookie called VisitorName with the value of
'George' and it will expire after 10 months from the current date.
path
If a page www.w3resource.com/javascript/ sets a cookie then all the pages in that directory (i.e.
../javascript) and its subdirectories will be able to read the cookie. But a page in
www.w3resource/php/ directory can not read the cookie. Usually, the path is set to root level
[VAPM,Almala-Inst.Code-1095
]3 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
directory ( '/' ) , which means the cookie is available for all the pages of your site. If you want the
cookie to be readable in a specific directory called php, add path=/php;.
Here is the example where we have set a specific path called 'php'
document.cookie= "VisiterName=George;expires=Mon,12Jun2011:00:00:00"
+ ";path=/php;";
Copy
In the following code here we have specified that the cookie is available to all subdirectories of
the domain.
document.cookie= "VisiterName=George;expires=Mon,12Jun2011:00:00:00"
+ ";path=/;";
Copy
domain
Some websites have lots of domains. The purpose of the 'domain' is to allow cookies to other
subdomains. For example a web portal call 'mysite'. It's main site is http://www.mysite.com with
a matrimonial site (http://matimonial.mysite.com), a financial site (http://financial.mysite.com)
and a travel site (http://travel.mysite.com). By default, if a web page on the travel site sets a
cookie, pages on the financial site cannot read that cookie. But if you add domain = mysite to a
cookie, all domain ending with 'mysite' can read the cookie. Note that the domain name must
contain at least two dots (.), e.g., ".mysite.com"
document.cookie= "VisiterName=George;expires=Mon,12Jun2011:00:00:00"
[VAPM,Almala-Inst.Code-1095
]4 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Copy
Secure
The last part of the cookie string is the secure part which is a boolean value. The default value is
false. If the cookie is marked secure (i.e. secure value is true) then the cookie will be sent to web
server and try to retrieve it using a secure communication channel. This is applicable for those
servers which have SSL (Secure Sockets Layer) facility.
We have already learned the various parts of the cookie like name, value, expires, path, domain,
and security. Let's create a simple cookie.
In the following example, we have written a function name 'CookieSet' and set some of its
attributes.
Example:
In the following web document four parameters name, value, expires and path parts sent to the
function 'CookieSet'. The secure and domain parts are not essential here. Empty values set to
expires and path parts and there is a checking for expires and path parts. If expires receive empty
value it will set the expires date 9 months from the current date and if path receives empty value
then current directory and subdirectories will be the path. The toUTCString converts the date to a
string, using the universal time convention.
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
</head>
[VAPM,Almala-Inst.Code-1095
]5 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
<body>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
cvalue = encodeURIComponent(cValue);
if (cExpires == "")
cdate.setMonth(cdate.getMonth() + 9);
cExpires = cdate.toUTCString();
if (cPath != "")
CookieSet("Name","George ","","");
alert(document.cookie)
//]]>
</script>
</body>
[VAPM,Almala-Inst.Code-1095
]6 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
</html>
Copy
Example: Receive real data from the user and store it in a cookie.
The following web document receives real data from the user and stores it in a cookie for next
one year from the current date.
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
</head>
<body>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
document.cookie = final_cookie;
[VAPM,Almala-Inst.Code-1095
]7 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
alert(final_cookie);
//]]>
</script>
</body>
</html>
Copy
Delete a cookie
Deleting a cookie is extremely easy. To delete a cookie first accept the name of the cookie and
create a cookie with the same name and set expiry date one day ago from the current date. As the
expiry date has already passed the browser removes the cookie immediately. It is not confirmed
that the cookie has deleted during the current session, some browser maintains the cookie until
restart the browser. To see the example read A real example on Cookiespage.
When a browser opens a web page, the browser reads the cookies (provided it has already stored
it) that have stored on your machine. We used document.cookie to retrieve the information about
the cookie.
Example:
In the following web document, we receive a name from the visitor and stored it in the cookie
called "Name".
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
[VAPM,Almala-Inst.Code-1095
]8 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
</head>
<body>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
curdate.setMonth(curdate.getMonth() + 6);
document.cookie = final_cookie;
alert(final_cookie);
//]]>
</script>
</body>
</html>
Copy
[VAPM,Almala-Inst.Code-1095
]9 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
In the following web document, we will read the stored cookie and retrieves its value.
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
</head>
<body>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
if (document.cookie.length > 0)
offset = document.cookie.indexOf(search_cookie)
if (offset != -1)
offset += search_cookie.length
end = document.cookie.indexOf(";",offset)
if (end == -1)
[VAPM,Almala-Inst.Code-1095
]10 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
end = document.cookie.length
alert(decodeURIComponent(document.cookie.substring(offset, end)))
//]]>
</script>
</head>
</body>
</html>
Copy
In the following web document, if a visitor registered his name, his name will be displayed if he
returns back to this page for the next nine months. When the visitor registered his name a cookie
is stored in the visitor hard drive, to delete this cookie see the next example.
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<title>JavaScript Cookie</title>
<script type="text/javascript">
[VAPM,Almala-Inst.Code-1095
]11 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
function register(name)
curdate.setMonth(curdate.getMonth() + 9);
cookieExpires = curdate.toUTCString();
document.cookie = final_cookie;
function getCookie(cookie_name)
if (document.cookie.length > 0)
start_position = document.cookie.indexOf(search_cookie)
if (start_position!= -1)
start_position += search_cookie.length
if (end_position == -1)
end_position = document.cookie.length
[VAPM,Almala-Inst.Code-1095
]12 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
//]]>
</script>
</head>
<body>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
if (username)
if (username == null)
document.write('onClick="register(this.form.username.value); history.go(0)">');
document.write('</form>');
[VAPM,Almala-Inst.Code-1095
]13 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
//]]>
</script>
</body>
</html>
Copy
To delete the above cookie from your hard drive use the following web document.
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
function register(name)
nowDate.setMonth(nowDate.getMonth() + 9);
cookieExpires = nowDate.toUTCString();
document.cookie = final_cookie;
[VAPM,Almala-Inst.Code-1095
]14 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
function getCookie(cookie_name)
if (document.cookie.length > 0)
start_position = document.cookie.indexOf(search_cookie)
if (start_position!= -1)
start_position += search_cookie.length
if (end_position == -1)
end_position = document.cookie.length
//]]>
</script>
</head>
<body>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
[VAPM,Almala-Inst.Code-1095
]15 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
if (yourname)
if (yourname == null)
document.write('onClick="register(this.form.username.value); history.go(0)">');
document.write('</form>');
//]]>
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
[VAPM,Almala-Inst.Code-1095
]16 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
</head>
<body>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="red">Red</option>
</select>
<script type="text/javascript">
function display()
document.bgColor = value;
</script>
</body>
</html>
[VAPM,Almala-Inst.Code-1095
]17 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
JavaScript Cookies
A cookie is an amount of information that persists between a server-side and a client-side.
A web browser stores this information at the time of browsing.
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.
next →← prev
JavaScript Cookies
A cookie is an amount of information that persists between a server-side and a client-
side. A web browser stores this information at the time of browsing.
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.
[VAPM,Almala-Inst.Code-1095
]18 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
1. document.cookie="name=value";
[VAPM,Almala-Inst.Code-1095
]19 | P a g e
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Form Object
Form Object:
form object is a Browser object of JavaScript used to access an HTML form. If a user wants to
access all forms within a document then he can use the forms array. The form object is actually a
property of document object that is uniquely created by the browser for each form present in a
document. The properties and methods associated with form object are used to access the form
fields, attributes and controls associated with forms.
Syntax:
<form> . . . </form>
action:
action property of form object is used to access the action attribute present in HTML associated
with the <form> tag. This property is a read or write property and its value is a string.
elements[]:
elements property of form object is an array used to access any element of the form. It contains
all fields and controls present in the form. The user can access any element associated with the
form by using the looping concept on the elements array.
encoding:
The encoding property of a form object is used to access the enctype attribute present in HTML
associated with the <form> tag. This property is a read or write property and its value is a string.
This property helps determine the way of encoding the form data.
length:
length property of form object is used to specify the number of elements in the form. This
denotes the length of the elements array associated with the form.
method:
method property of form object is used to access the method attribute present in HTML
associated with the <form> tag. This property is a read or write property and its value is a string.
This property helps determine the method by which the form is submitted.
name:
name property of form object denotes the form name.
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
button:
The button property of form object denotes the button GUI control placed in the form.
checkbox:
checkbox property of form object denotes the checkbox field placed in the form.
FileUpload:
FileUpload property of form object denotes the file upload field placed in the form..
hidden:
The hidden property of form object denotes the hidden field placed in the form.
password:
password property of form object denotes the object that is placed as a password field in the
form.
radio:
radio property of form object denotes the radio button field placed in the form.
reset:
As the name implies, the reset property of form object denotes the object placed as reset button
in the form.
select:
select property of form object denotes the selection list object placed in the form.
submit:
submit property of form object denotes the submit button field that is placed in the form.
text:
text property of form object denotes the text field placed in the form.
textarea:
textarea property of form object denotes the text area field placed in the form.
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
next word, ACTION="" tells the way the user wants the browser to handle the form when it is
submitted to a CGI program running on the server. It can also be left as not specified with any of
the above properties. This means the URL for the CGI program is then omitted.
The METHOD="GET" defines that the method data is passed to the server when the form is
submitted.
INPUT TYPE="text" defines the object used as a text box with the name of the text box as a test
with no initial value specified. INPUT TYPE="button" defines the object used as a button with
the name of the button object as an example. The value is specified as Click and when the button
is clicked, the onClick event handler fires and the function associated with it (testfunc(this.form))
is called.
submit():
submit() method of form object is used to submit a form.
handleEvent():
handleEvent() method of form object is used to start or invoke a form’s event handler for a
specified event.
Hidden Object
Hidden object represents a hidden input field in an HTML form and it is invisible to the user.
This object can be placed anywhere on the web page.
It is used to send hidden form of data to a server.
Syntax:
<input type= ―hidden‖>
Property Description
Name It sets and returns the value of the name attribute of the hidden input field.
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Value It sets or returns the value of the value attribute of the hidden input field.
3. Password Object
Property Description
maxLength It sets or returns the maximum number of characters allowed in a password filed.
Name It sets or returns the value of the name attribute of a password field.
Value It sets or returns the value of the attribute of the password field.
Method Description
4. Checkbox Object
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
It allows the user to select one or more options from the available choices.
Syntax:
<input type= ―checkbox‖>
Property Description
Method Description
5. Select Object
Collection Description
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Property Description
selectedIndex It sets or returns the index of the selected option in a dropdown list.
Method Description
6. Option Object
Property Description
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Value It sets or returns the value to the server if the option was selected.
Methods Description
<html>
<head>
<script type="text/javascript">
function optionfruit(select)
{
var a = select.selectedIndex;
var fav = select.options[a].value;
if(a==0)
{
alert("Please select a fruit");
}
else
{
document.write("Your Favorite Fruit is <b>"+fav+".</b>");
}
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
}
</script>
</head>
<body>
<form>
List of Fruits:
<select name="fruit">
<option value="0">Select a Fruit</option>
<option value="Mango">Mango</option>
<option value="Apple">Apple</option>
<option value="Banana">Banana</option>
<option value="Strawberry">Strawberry</option>
<option value="Orange">Orange</option>
</select>
<input type="button" value="Select" onClick="optionfruit(this.form.fruit);">
</form>
</body>
</html>
Output:
7. Radio Object
Syntax:
<input type= ―radio‖>
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Property Description
Name It sets or returns the value of the name attribute of a radio button.
Method Description
8. Text Object
Syntax:
<input type= ―text‖>
Property Description
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Name It sets or returns the value of the name attribute of a text field.
maxLength It sets or returns the maximum number of characters allowed in a text field.
9. Textarea Object
Syntax:
<textarea> . . . </textarea>
Property Description
Name It sets or returns the value of the name attribute of a text field.
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
https://www.tutorialride.com/javascript/javascript-dom-frame-object.htm
JavaScript Events
Example
Try this code »
Example
Try this code »
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
In general, the events can be categorized into four main groups — mouse events, keyboard
events, form events and document/window events. There are many other events, we will learn
about them in later chapters. The following section will give you a brief overview of the most
useful events one by one along with the real life practice examples.
Mouse Events
A mouse event is triggered when the user click some element, move the mouse pointer over an
element, etc. Here're some most important mouse events and their event handler.
Example
Try this code »
Example
Try this code »
Example
Try this code »
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Example
Try this code »
Keyboard Events
A keyboard event is fired when the user press or release a key on the keyboard. Here're some
most important keyboard events and their event handler.
Example
Try this code »
Example
Try this code »
Example
Try this code »
Form Events
A form event is fired when a form control receive or loses focus or when the user modify a form
control value such as by typing text in a text input, select any option in a select box etc. Here're
some most important form events and their event handler.
Example
Try this code »
<script>
function highlightInput(elm){
elm.style.background = "yellow";
}
</script>
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Example
Try this code »
Example
Try this code »
Example
Try this code »
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Document/Window Events
Events are also triggered in situations when the page has loaded or when user resize the browser
window, etc. Here're some most important document/window events and their event handler.
Example
Try this code »
Example
Try this code »
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Example
Try this code »
<p id="result"></p>
<script>
function displayWindowSize() {
var w = window.outerWidth;
var h = window.outerHeight;
var txt = "Window size: width=" + w + ", height=" + h;
document.getElementById("result").innerHTML = txt;
}
window.onresize = displayWindowSize;
</script>
https://www.tutorialrepublic.com/javascript-tutorial/javascript-events.php
<!DOCTYPE html>
<html>
<body>
<form>
<option>Apple</option>
<option>Pear</option>
<option>Banana</option>
<option>Orange</option>
</select>
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
</form>
<br>
<p>Click the button to add a "Kiwi" option at the end of the dropdown list.</p>
******************************************************************************
<script>
function myFunction() {
var x = document.getElementById("mySelect");
x.add(option);
</script>
</body>
</html>
function getOption(){
if(select.options.length > 0) {
} else {
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
function addOption(){
function removeOption(){
select.options[select.selectedIndex] = null;
function removeAllOptions(){
select.options.length = 0;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
<select id="dynamic-select">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<script src="script.js"></script>
</body>
</html>
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Deleting Properties
The delete keyword deletes a property from an object:
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
delete person.age;
The delete keyword deletes both the value of the property and the property
itself.
After deletion, the property cannot be used before it is added back again.
JavaScript Arrays
An array is an object that can store a collection of items. Arrays become really useful
when you need to store large amounts of data of the same type. Suppose you want to store
details of 500 employees. If you are using variables, you will have to create 500 variables
whereas you can do the same with a single array. You can access the items in an array by
referring to its indexnumber and the index of the first element of an array is zero.
Example
var cars = ["Saab", "Volvo", "BMW"];
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
However, what if you want to loop through the cars and find a specific one? And what if you
had not 3 cars, but 300?
An array can hold many values under a single name, and you can access the values by
referring to an index number.
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array_name = [item1, item2, ...];
Example
var cars = ["Saab", "Volvo", "BMW"];
Spaces and line breaks are not important. A declaration can span multiple lines:
Example
var cars = [
"Saab",
"Volvo",
"BMW"
];
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
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/>");
}
</script>
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to fruits
New element can also be added to an array using the length property:
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits
WARNING !
Adding elements with high indexes can create undefined "holes" in an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[6] = "Lemon"; // adds a new element (Lemon) to fruits
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
The elements will be separated by a specified separator. The default separator is comma (,).
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse the
code.
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Syntax
1. new Function ([arg1[, arg2[, ....argn]],] functionBody)
Parameter
arg1, arg2, .... , argn - It represents the argument used by function.
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Method Description
apply() It is used to call a function contains this value and a single array of
arguments.
call() It is used to call a function contains this value and an argument list.
Example 2
Let's see an example to display the power of provided value.
<script>
var pow=new Function("num1","num2","return Math.pow(num1,num2)");
document.writeln(pow(2,3));
</script>
Functions are very important and useful in any programming language as they make the
code reusable A function is a block of code which will be executed only if it is called. If you
have a few lines of code that needs to be used several times, you can create a function
including the repeating lines of code and then call the function wherever you want.
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Syntax:
function functionname()
<html>
<head>
<title>Functions!!!</title>
<script type="text/javascript">
function myFunction()
myFunction();
</script>
</head>
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
<body>
</body>
</html>
You can create functions with arguments as well. Arguments should be specified within
parenthesis
Syntax:
function functionname(arg1, arg2)
You can also create JS functions that return values. Inside the function, you need to use the
keyword return followed by the value to be returned.
Syntax:
function functionname(arg1, arg2)
return val1;
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
return sum;
}
var firstNo = 78;
var secondNo = 22;
document.write(firstNo + " + " + secondNo + " = " + returnSum(firstNo,secondNo));
</script>
</head>
<body>
</html>
Introduction
A string is a sequence of one or more characters that may consist of letters, numbers, or
symbols. Each character in a JavaScript string can be accessed by an index number, and
all strings have methods and properties available to them.
In order to test the difference between the two, we will initialize a string primitive and a
string object.
typeof stringPrimitive;
Output
string
In the second example, we used new String() to create a string object and assign it to
a variable.
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
typeof stringObject;
Output
Object
Most of the time you will be creating string primitives. JavaScript is able to access and
utilize the built-in properties and methods of the String object wrapper without
actually changing the string primitive you've created into an object.
While this concept is a bit challenging at first, you should be aware of the distinction
between primitive and object. Essentially, there are methods and properties available to
all strings, and in the background JavaScript will perform a conversion to object and
back to primitive every time a method or property is called.
To demonstrate, we will create a string with the value How are you?.
H o w a r e y o u ?
0 1 2 3 4 5 6 7 8 9 10 11
The first character in the string is H, which corresponds to the index 0. The last character
is ?, which corresponds to 11. The whitespace characters also have an index, at 3 and 7.
Being able to access every character in a string gives us a number of ways to work with
and manipulate strings.
1. charAt(x) Returns the character at the “x” position within the string.
//charAt(x)
console.log(myString.charAt(7));
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
//output: F
2. charCodeAt(x) Returns the Unicode value of the character at position “x” within the
string.
//charAt(position)
var message="jquery4u"
//alerts "q"
alert(message.charAt(1))
3. concat(v1, v2,…) Combines one or more strings (arguments v1, v2 etc) into the
existing one and returns the combined string. Original string is not modified.
//concat(v1, v2,..)
var message="Sam"
alert(final)
//fromCharCode(c1, c2,...)
console.log(String.fromCharCode(97,98,99,120,121,122))
//output: abcxyz
console.log(String.fromCharCode(72,69,76,76,79))
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
//output: HELLO
//(PS - I have no idea why you would use this? any ideas?)
5. indexOf(substr, [start]) Searches and (if found) returns the index number of the
searched character or substring within the string. If not found, -1 is returned. “Start” is
an optional argument specifying the position within string to begin the search. Default is
0.
//indexOf(char/substring)
if (sentence.indexOf("Sam")!=-1)
alert("Sam is in there!")
6. lastIndexOf(substr, [start]) Searches and (if found) returns the index number of the
searched character or substring within the string. Searches the string from end to
beginning. If not found, -1 is returned. “Start” is an optional argument specifying the
position within string to begin the search. Default is string.length-1.
//lastIndexOf(substr, [start])
console.log(myString.lastIndexOf('r'));
//output: 11
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
console.log(isInt);
//output: 999
console.log(isInt);
//output: null
//replace(substr, replacetext)
console.log(myString.replace(/JavaScript/i, "jQuery"));
//replace(regexp, replacetext)
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
9. search(regexp) Tests for a match in a string. It returns the index of the match, or -1 if
not found.
//search(regexp)
console.log(isInt);
//output: 0
console.log(isInt);
//output: -1
10. slice(start, [end]) Returns a substring of the string based on the “start” and “end”
index arguments, NOT including the “end” index itself. “End” is optional, and if none is
specified, the slice includes all characters from “start” to end of string.
//slice(start, end)
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
var text="excellent"
11. split(delimiter, [limit]) Splits a string into many according to the specified delimiter,
and returns an array containing each element. The optional “limit” is an integer that lets
you specify the maximum number of elements to return.
//split(delimiter)
var word=message.split("l")
12. substr(start, [length]) Returns the characters in a string beginning at “start” and
through the specified number of characters, “length”. “Length” is optional, and if omitted,
up to the end of the string is assumed.
//substring(from, to)
var text="excellent"
13. substring(from, [to]) Returns the characters in a string between “from” and “to”
indexes, NOT including “to” inself. “To” is optional, and if omitted, up to the end of the
string is assumed.
//substring(from, [to])
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
myString = myString.substring(0,10);
console.log(myString)
//output: javascript
14. toLowerCase() Returns the string with all of its characters converted to lowercase.
//toLowerCase()
myString = myString.toLowerCase();
console.log(myString)
15. toUpperCase() Returns the string with all of its characters converted to uppercase.
//toUpperCase()
myString = myString.toUpperCase();
console.log(myString)
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
String Properties
Property Description
String Methods
Method Description
charCodeAt(position) Returns a number indicating the Unicode value of the character at the given
position (in Number).
concat([string,,]) Joins specified string literal values (specify multiple strings separated by
comma) and returns a new string.
indexOf(SearchString, Returns the index of first occurrence of specified String starting from
Position) specified number index. Returns -1 if not found.
lastIndexOf(SearchString, Returns the last occurrence index of specified SearchString, starting from
Position) specified position. Returns -1 if not found.
match(RegExp) Search a string for a match using specified regular expression. Returns a
matching array.
replace(searchValue, Search specified string value and replace with specified replace Value string
replaceValue) and return new string. Regular expression can also be used as searchValue.
slice(startNumber, Extracts a section of a string based on specified starting and ending index
endNumber) and returns a new string.
split(separatorString, Splits a String into an array of strings by separating the string into substrings
limitNumber) based on specified separator. Regular expression can also be used as
separator.
substr(start, length) Returns the characters in a string from specified starting position through
the specified number of characters (length).
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Method Description
substring(start, end) Returns the characters in a string between start and end indexes.
Method Description
link() Wraps a string in <a>tag where href attribute value is set to specified string.
VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]
Method Description
VAPM,Almala-Inst.Code-1095
October 7, MR.SWAMI R.S. {MOBILE NO :- +91-8275265361]
2019
Validation Code
<html>
<head>
<script>
function validateform()
{
var
name=document.myform.name.value;
var
password=document.myform.password.v
alue;
Slider Show
<html>
<head>
<script>
Silder=new
Array('download1.jpg','download2.jpg','download3.jpg','download4.jpg','download5.jpg');
i=0;
function display(sn)
{
i=i+sn;
if(i>Silder.length-1)
{
i=0;
}
if(i<0)
{
i=Silder.length-1;
}
document.SlideID.src=Silder[i];
}
</script>
</head>
<body>
<center>
<h1>Nature ko enjoy kare!</h1>
Menu
<html>
<head>
<script>
function menuitem()
{
var
s=document.getElementById("select");
var str=s.options[s.selectedIndex].value;
</body>
</head>
</html>
Rollover
<html>
<body>
<a>
<img
src="Chrysanthemum.jpg"
onmouseover="src=Desert.jpg"
onmouseout="src=Koala.jpg">
</a>
</body>
</html>
Or
<html>
<head>
<script>
function display1()
{
document.pic.src='file:\\\C://Users//Public//Pictures//Sample Pictures//Desert.jpg';
document.getElementById('p').innerHTML="This Desert Image.";
}
function display2()
{
document.pic.src='file:\\\C://Users//Public//Pictures//Sample Pictures//Koala.jpg';
document.getElementById('p').innerHTML="This Koala Image.";
}
</script>
</head>
<body>
<a onmouseover="display1()"><h1>Dersert</h1></a>
<a onmouseout="display2()"><h1>Koala</h1></a>
<a>
<img src='file:\\\C://Users//Public//Pictures//Sample
Pictures//Chrysanthemum.jpg'name='pic'>
</a>
<p id="p">Images</p>
</body>
</html>
Intrinsic
<html>
<body>
<form name="frm1" method="post">
Name<input type="text"
name="t1"><br>
Password<input type="text"
name="t2"><br>
<button
onclick="javascript:document.forms.formn
ame.submit()">submit</button>
<button
onclick="javascript:document.forms.formn
ame.reset()">reset</button>
</form>
</body>
</html>
Dynamically
<!DOCTYPE html>
<html>
<body>
<form>
<select id="mySelect" size="8">
<option>Apple</option>
<option>Pear</option>
<option>VAPM</option>
<option>Banana</option>
<option>Orange</option>
</select>
</form>
<br>
<script>
function myFunction() {
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = prompt("Enter the Student Name=");
x.add(option);
}
</script>
</body>
</html>
Frame
<html>
9 <head>
<title>Example of HTML
Frames using row and Cols
attribute</title>
</head>
</frameset>
Adhar Card Validation Program
</html>
<html>
<head>
<script>
function show()
{
adhar =
document.getElementBy
Id("txtaadhar").value;
var adharcard =
/^\d{12}$/;
var adharsixteendigit =
/^\d{16}$/;
if (adhar != '') {
if
(!adhar.match(adharcar
d))
{
alert("Invalid
Aadhar Number");
return false;
}
}
if (adhar != '')
{
if(!adhar.match(adharsixteendigit))
{
alert("Invalid Aadhar Number");
return false;
}
}
}
</script>
</head>
<body>
Enter the Adhar Card No.<input type="text" id="txtaadhar"><br>
<button onclick="show()">Adhar Card</button>
</body>
</html>
The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.
There are no official standards for the Browser Object Model (BOM).
Since modern browsers have implemented (almost) the same methods and properties for
JavaScript interactivity as methods and properties of the BOM.
The window object is supported by all browsers. It represents the browser's window.
All global JavaScript objects, functions, and variables automatically become members of the
window object.
URL
The URL of the page to open in the new window. This argument could be blank.
windowName
A name to be given to the new window. The name can be used to refer this window again.
windowFeatures
A string that determines the various window features to be included in the popup window (like
status bar, address bar etc)
The following code opens a new browser window with standard features.
fullscreen=yes|no|1|0 Whether or not to display the browser in full-screen mode. Default is no. A
window in full-screen mode must also be in theater mode. IE only
left=pixels The left position of the window. Negative values not allowed
1 |Page
location=yes|no|1|0 Whether or not to display the address field. OperaVonly
APM ALMALA
September
MR.SWAMI R.S. {MOBILE NO:- +91-8275265361}
17, 2019
scrollbars=yes|no|1|0 Whether or not to display scroll bars. IE, Firefox & Opera only
titlebar=yes|no|1|0 Whether or not to display the title bar. Ignored unless the calling application is an
HTML Application or a trusted dialog box
toolbar=yes|no|1|0 Whether or not to display the browser toolbar. IE and Firefox only
top=pixels The top position of the window. Negative values not allowed
Window.close()
This method is used to close the window which are opened by window.open() method.
Syntax:
window.close()
Window.blur() Method
The blur() method is used to remove focus from the current window. i.e, It send the new open
Window to the background.
Syntax:
Window.blur()
message is a string of text to display to the user.It can be omitted if there is nothing to
show in the prompt window i.e. it is optional.
default is a string containing the default value displayed in the text input field. It is also
optional.
prompt.html
The Window scrollTo() method is used to scroll to a particular set of coordinates in the
document.
Syntax:
window.scrollTo(x-coord, y-coord)
Parameters: The scrollTo() method accepts two parameters as described below:
x-coord: It is the pixel along the horizontal axis of the document that is displayed in the
upper left. It is the required field.
y-coord: It is the pixel along the vertical axis of the document that is displayed in the upper
left. It is the required field.
ScrollBarDemo.html
ScrollBarDemo2.html
By writing some text to the newly created window we can change the contents of a window.
multiple.html
JavaScript Security
Since its release, there have been several JavaScript security issues that have gained widespread
attention. For one, the way JavaScript interacts with the DOM poses a risk for end users by
enabling malicious actors to deliver scripts over the web and run them on client computers.
There are two measures that can be taken to contain this JavaScript security risk. First is
sandboxing, or running scripts separately so that they can only access certain resources and
perform specific tasks. The second measure is implementing the same origin policy, which
prevents scripts from one site from accessing data that is used by scripts from other sites. Many
JavaScript security vulnerabilities are the result of browser authors failing to take these measures
to contain DOM-based JavaScript security risks.
One of the most common JavaScript security vulnerabilities is Cross-Site Scripting (XSS).
Cross-Site Scripting vulnerabilities enable attackers to manipulate websites to return malicious
scripts to visitors. These malicious scripts then execute on the client side in a manner determined
by the attacker. XSS vulnerabilities can exist when browser or application authors fail to
implement the same origin policy and can be prevented by following correct development
techniques. If XSS vulnerabilities aren’t remediated, they can result in user data theft, account
tampering, malware spreading or remote control over a user’s browser.
Another common JavaScript security vulnerability is Cross-Site Request Forgery (CSRF). Cross-
Site Request Forgery vulnerabilities allow attackers to manipulate victims’ browsers to take
unintended actions on other sites. This is possible when target sites authenticate requests solely
using cookies and attackers are able to send requests carrying users’ cookies. This JavaScript
security issue can lead to account tampering, data theft, fraud and more. Both Cross-Site
Scripting and Cross-Site Request Forgery vulnerabilities exist in the application layer and require
that correct development techniques are followed in order to be avoided.
There are a variety of other common JavaScript security issues that can increase risks for users.
These issues include improper client-server trust relationships, vulnerabilities in browser and
browser plugin code, and incorrect implementation of sandboxing or same origin policy. And for
Node.js-based server side applications, there may be many other security vulnerabilities,
including SQL Injection, Command Injection, and others. The only way for organizations to
avoid these JavaScript security risks is to develop and source applications that are free of
JavaScript security vulnerabilities. Many organizations use JavaScript security analyzers to test
for and remediate these vulnerabilities.
JavaScript security analyzers are JavaScript security tools that perform code analysis on client-
side applications. These analyzers can typically test for JavaScript security vulnerabilities, issues
in implementation, configuration errors and other risks that can be exploited by attackers. The
Veracode platform provides JavaScript security analysis through its automated cloud-based
service. Veracode assesses web applications and client-side technologies in a running
environment in order to discover JavaScript security vulnerabilities and other issues.
JavaScript is designed as an open scripting language. It is not intended to replace proper security
measures, and should never be used in place of proper encryption. See also my article
about cross site scripting.
JavaScript has its own security model, but this is not designed to protect the Web site owner or
the data passed between the browser and the server. The security model is designed to protect the
user from malicious Web sites, and as a result, it enforces strict limits on what the page author is
allowed to do. They may have control over their own page inside the browser, but that is where
their abilities end.
JavaScripts cannot read or write files on users' computers (File API - not currently supported
by many browsers - allows files to be read by scripts if the user specifically chooses to allow
it), though they can cause the browser to load remote pages and resources like scripts or
images, which the browser may choose to cache locally. They cannot create files on the
server (except by communicating with a server side script that creates files for them). The
only thing they can store on the user's computer are cookies (and Web Storage - similar to
cookies but with more data types - in newer browsers).
They are allowed to interact with other pages in a frameset, if those frames originate from the
same Web site, but not if they originate from another Web site (the postMessage method
from HTML 5 does safely extend this capability, but I will not cover that here). Some
browsers will even treat different port numbers on the same server as a different Web site.
JavaScript cannot be used to set the value attribute of a file input, and will not be allowed to
use them to upload files without permission.
JavaScript cannot read what locations a user has visited by reading them from the location
object, although it can tell the browser to jump back or forward any number of steps through
the browser history. It cannot see what other Web pages the user has open.
JavaScript cannot access the cookies or variables from other sites.
It cannot see when the user interacts with other programs, or other parts of the browser
window.
It cannot open windows out of sight from the user or too small for the user to see, and in
most browsers, it cannot close windows that it did not open.
<html>
<body>
<script>
var myWindow;
function openWin() {
myWindow = window.open("", "myWindow", "width=200,height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
//myWindow.opener.document.write("<p>This is the source window!</p>");
}
function closeWin() {
myWindow.close();
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
function scrollWindow() {
window.scrollTo(0, 100);
}
</script>
</head>
<body>
<h2>Reserved Words</h2>
<hr>
<p>You cannot use reserved words as variables, labels, or function names:</p>
<hr>
<br>
abstract<br><br>
arguments<br><br>
boolean<br><br>
break<br><br>
byte<br><br>
case<br><br>
catch<br><br>
char<br><br>
class<br><br>
const<br><br>
continue<br><br>
debugger<br><br>
default<br><br>
delete<br><br>
do<br><br>
double<br><br>
else<br><br>
enum<br><br>
eval<br><br>
export<br><br>
extends<br><br>
false<br><br>
final<br><br>
finally<br><br>
float<br><br>
for<br><br>
function<br><br>
goto<br><br>
if<br><br>
implements<br><br>
import<br><br>
in<br><br>
instanceof<br><br>
int<br><br>
interface<br><br>
let<br><br>
long<br><br>
native<br><br>
new<br><br>
null<br><br>
package<br><br>
private<br><br>
protected<br><br>
public<br><br>
return<br><br>
short<br><br>
static<br><br>
super<br><br>
switch<br><br>
synchronized<br><br>
this<br><br>
throw<br><br>
throws<br><br>
transient<br><br>
true<br><br>
try<br><br>
typeof<br><br>
var<br><br>
void<br><br>
volatile<br><br>
while<br><br>
with<br><br>
yield<br><br>
</body>
</html>
Timing Events
The window object allows execution of code at specified time intervals.
setTimeout(function, milliseconds)
Executes a function, after waiting a specified number of milliseconds.
setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function
continuously.
The setTimeout() and setInterval() are both methods of the HTML DOM
Window object.
window.clearTimeout(timeoutVariable)
If the function has not already been executed, you can stop the execution by
calling the clearTimeout() method:
Example
Same example as above, but with an added "Stop" button:
window.setInterval(function, milliseconds);
The second parameter indicates the length of the time-interval between each
execution.
This example executes a function called "myTimer" once every second (like a
digital watch).
10 | P a g e VAPM ALMALA
September
MR.SWAMI R.S. {MOBILE NO:- +91-8275265361}
17, 2019
Example
Display the current time:
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
window.clearInterval(timerVariable)
Example
Same example as above, but we have added a "Stop time" button:
<p id="demo"></p>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
11 | P a g e VAPM ALMALA
September
MR.SWAMI R.S. {MOBILE NO:- +91-8275265361}
17, 2019
12 | P a g e VAPM ALMALA