JavaScript-JS
JavaScript-JS
UNIT-II: JAVASCRIPT
The Basic of Java script: Objects, Primitives, Operations and Expressions, Screen Output and
Keyboard Input, Control Statements, Object Creation and Modification, Arrays, Functions,
Constructors, Pattern Matching using Regular Expressions
DHTML: Positioning Moving and Changing Elements
ORIGINS:
JavaScript was originally developed at Netscape by Brendan Eich. Initially named Mocha but
soon after was renames LiveScript. In late 1995, LiveScript became a joint venture of Netscape and
Sun Micro Systems and its name changed again to JavaScript. A language standard for JavaScript
was developed by European Computer Manufacturers Association (ECMA) as ECMA – 262. This
standard is now in Version6. Since 2016 new versions are named by year (ECMAScript 2016 / 2017
/ 2018). The official name of this standard language is ECMA Script, but it becomes popular with the
name “JavaScript”.
1. The Core
The core is the heart of the language includes its operators, expressions, statements and sub –
programs.
2. Client Side
Client – Side script is a collection of objects that supports the control of a browser and
interactions with users. For example, with JavaScript, an HTML document can respond to the
user inputs such as mouse clicks and keyboard events.
3. Server Side
Server – Side Script is a collection of objects that makes language useful on a web server. For
example, to communicate with database management system
USES OF JAVASCRIPT:
The original goal of JavaScript was to provide the programming capability at both server and
client ends of web connection.
Client Side Script can serve as an alternative to perform the tasks done at the server – side. It
reduces computational tasks on server side. But it cannot replace all server side computing which
include file operations, database access, networking, etc.
Interaction with the users through form elements such as buttons and menus can be conveniently
performed with the use of JavaScript.
JavaScript is event driven; it is meant that an HTML document with embedded JavaScript is
capable to respond to the user actions such as mouse clicks, button presses, keyboard strokes, etc.
DOM is the main capability of JavaScript that makes static HTML Documents as highly
dynamic, which allows accessing and modifying the style properties and content of the elements
of HTML document.
JavaScript can be used to create cookies.
JavaScript is used to validate the data on the web page before submitting it to the server.
Implicit embedding has the advantage of hiding the script from the browser user. When
scripts are embedded in HTML Document, they can appear in either head or body part of the HTML
document depending on the purpose. Scripts that produce the content only when as a response to the
user actions are placed in head section of the document. Scripts that are to be interpreted just once,
only when the interpreter finds are placed in the body section of the document.
PRIMITIVE DATA TYPES
Java script has five primitive types: Number, String, Boolean, Undefined and Null. Undefined and
Null are often called trivial types.
All numerical literals are primitive values of type Number. The Number type values are
represented internally in double – precision floating point form. Numerical Literals in a script
can be integers or floating point values.
A string literal is a sequence of characters delimited by either single quotes or double quotes.
String literals can also include escape characters such as \t, \n,…...
The only values of type Boolean are true and false. These values are usually computed as the
result of evaluating a relational or Boolean expression.
If a variable has been explicitly declared but not assigned a value. It has value undefined.
Null indicates no value. A variable is null if it has not been explicitly declared. If an attempt
is made to use a variable whose value is null, it causes a runtime error.
DECLARING VARIABLES
In JavaScript, variables are dynamic typed this means that the variable can be used for any
type. Variables are not typed. A variable can have the value of any primitive type or it can be a
reference to any object.
The type of the value of the variable in a program can be determined by the interpreter.
Interpreter converts the type of a value to whatever is needed for the context.
A variable can be declared either by assigning it a value, then the interpreter implicitly declares it or
declare it explicitly using the keyword var.
Examples:
var counter;
var index=0;
var pi=3.14159265;
var status=true;
var color= “greeen”;
A variable that has been declared but not assigned a value has the value undefined.
Alert box is a very frequently useful to send or write cautionary messages to end user screen.
Alert box is created by alert method of window object as shown below.
When alert box is popup, the user has to click ok to continue browsing or to perform any
further operations.
Example:
<html>
<head>
<title> alert box </title>
<script language="JavaScript">
function add( )
{
a=20;
b=40;
c=a+b;
window.alert("This is for addition of 2 no's");
} document.write("Result is: "+c);
</script>
</head>
<body onload="add( )">
</body>
</html>
Output:
Result is 60
This is useful to verify or accept something from user. It is created by confirm method of
window object as shown below.
When the confirm box pop„s up, user must click either ok or cancel buttons to proceed. If
user clicks ok button it returns the boolean value true. If user clicks cancel button, it returns the
boolean value false.
Example: -
<HTML>
<HEAD>
<TITLE> Confirm </TITLE>
<script>
function sub( )
{
a=50;
b=45;
c=a-b;
x=window.confirm("Do you want to see subtraction of numbers")
;if(x==true)
{
document.write("result is :"+c);
}
else
{
document.write("you clicked cancel button");
}
}
</script>
</HEAD>
<BODY onload="sub( )">
To see the o/p in pop up box:
</BODY>
5
</HTML>
Output:
result is :5
When prompt dialog box arises user will have to click either ok button or cancel button after
entering input data to proceed. If user click ok button it will return input value. If user click cancel
button the value ―null will be returned.
Example:
<HTML>
<HEAD>
<TITLE> Prompt </TITLE>
<script>
function fact( )
{
var b=window.prompt("enter +ve integer :","enter here");
var c=parseInt(b);
a=1;
for(i=c;i>=1;i--)
{
a=a*i;
}
window.alert("factorial value :"+a);
}
</script>
</HEAD>
<BODY onload="fact( )">
</BODY>
</HTML>
Output:
Write ( ) Method:
The write( ) method in HTML is used to write some content or JavaScript code in a Document.
Here, exp1, exp2, exp3 ….. are all optional arguments, these are arguments are appended to the
document in order of occurrence
The writeln() method is identical to the document.write() method, with the addition of writing
a newline character after each statement.
Example:
<!DOCTYPE html>
<html>
<body>
<p>Note that write() does NOT add a new line after each statement:</p>
<script>
document.write("Hello World!");
document.write("Have a nice
day!");
</script>
<p>Note that writeln() add a new line after each statement:</p>
<script>
document.writeln("Hello World!");
document.writeln("Have a nice
day!");
</script>
</body>
</html
Output:
Note that write() does NOT add a new line after each statement:
Hello World!
Have a nice day!
OPERATORS IN JAVASCRIPT
In JavaScript, an operator is a special symbol used to perform operations on operands (values
and variables).
For example, 2 + 3; // 5
Here + is an operator that performs addition, and 2 and 3 are operands.
JavaScript supports the following types of operators.
Arithmetic Operators
Comparison (or Relational) Operators
Logical Operators
Assignment Operators
Conditional (or ternary) Operators
ARITHMETIC OPERATORS
JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then −
5
% (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6
++ (Increment)
Increases an integer value by one
Ex: A++ will give 11
7
-- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9
COMPARISON OPERATORS
Comparison Operators also called relational operators, used to write conditions in the statements
like if, if – else, switch, loop statements. Expressions that include these set of operators
evaluated to true or false.
JavaScript supports the following comparison operators −
Assume variable A holds 10 and variable B holds 20, then −
Sr.No. Operator & Description
1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition becomes
true.
Ex: (A == B) is not true.
2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal, then the
condition becomes true.
Ex: (A != B) is true.
3 > (Greater than)
Checks if the value of the left operand is greater than the value of the right operand, if
yes, then the condition becomes true.
Ex: (A > B) is not true.
4 < (Less than)
Checks if the value of the left operand is less than the value of the right operand, if yes,
then the condition becomes true.
Ex: (A < B) is true.
5 >= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the value of the right
operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.
6 <= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of the right
operand, if yes, then the condition becomes true. Ex: (A <= B) is true.
LOGICAL OPERATORS
Logical Operators are used to combine two or more conditions into single condition. For these
operators, and the logical expressions are evaluated to either true or false.
JavaScript supports the following logical operators −
S.No. Operator & Description
1 && (Logical AND)
If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT
operator will make it false.
Ex: ! (A && B) is false.
ASSIGNMENT OPERATORS
Assignment operators are used to assign a literal value or value of an expression to variable.
JavaScript supports the following assignment operators −
Sr.No. Operator & Description
1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
2 += (Add and Assignment)
It adds the right operand to the left operand and assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A
3 −= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C – A
4 *= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C * A
10
Example 1:
var txt1 =
"John"; var txt2
= "Doe";
var txt3 = txt1 + " " + txt2; // now txt3 contains “John Doe”
11
Example 2:
If a number and a string is added then the result will be the string
Example:
TYPE CONVERSIONS
There are two types of type conversions (or) typecasting,
Converting one type of data value to another type is called typecasting. If required JavaScript
engine automatically converts one type of value into another type. It will try to convert it to the right
type.
Example:
1. “Survey_number”+10
The result of above operation will get a string
“Survey_number 10”
2. 5*”12”
Second operand which is a String will automatically converted to number.
The result is 60.
3. 5*”Hello”
Second operand which is a String cannot be converted to number.
The result is NaN –Not a number.
When implicit type conversion is made, the result is always not as expected
Examples:
5 + null // returns 5 because null is converted to 0
"5" + null // returns "5null" because null is converted to "null"
"5" + 2 // returns "52" because 2 is converted to "2"
"5" - 2 // returns 3 because "5" is converted to 5
"5" * "2" // returns 10 because "5" and "2" are converted to 5 and 2
12
Number ( ):
Number() function in used to convert a value to a Number. It can convert any numerical
text and boolean value to a Number. In case of strings of non-numerics, it will convert it to a NaN
(Not a Number)
Example:
var s = "144";
var n = Number(s); // now n contain 144(Number)
var s = true;
var n = Number(s); // now n contain 1(Number)
Boolean ( ):
It converts any type of value to true or false
Example:
var s = 1;
var n = Boolean(s); // now n contain true(Boolean)
var s = “0”;
var n = Boolean(s); // now n contain false(Boolean)
var s = “20”;
var n = Boolean(s); // now n contain true(Boolean)
var s = “twenty”;
var n = Boolean(s); // now n contain true(Boolean)
parseInt ( ):
This function is used to convert a numerical string into integer, if string contains non –
numerical values then it returns NaN (Not a Number).
13
Example:
var s = “20”;
var n = parseInt(s); // now n contain 20 (integer)
var s = “twenty”;
var n = parseInt(s); // now n contain NaN (Not a Number)
var s = “19twenty”;
var n = parseInt(s); // now n contain 19 (integer)
Here, this function parses up to numerical characters when it finds non – numerical
character then it stops parsing.
parseFloat ( )
The parseFloat() function is used to convert the string into a floating-point number. If
the string does not contain a numeral value or if the first character of the string is not a Number
then it returns NaN i.e, not a number. It actually returns a floating-point number parsed up to that
point where it encounters a character that is not a Number.
Example:
var s = “20.56”;
var n = parseInt(s); // now n contain 20.56 (float value)
toString( )
The toString() method in Javascript is used with a number and converts the number to a
string. It is used to return a string representing the specified Number object.
Syntax:
num.toString(base) // base specifies the number system
Example:
var num=12;
document.write("Output : " + num.toString(2));
Here, it displays 1100 in binary number system
var num=12;
document.write("Output : " + num.toString(10));
Here it displays 12 in decimal number systems
var num=12;
document.write("Output : " + num.toString(8));
14
CONTROL STATEMENTS
Control Structures are used to control sequential flow of program execution in desired
manner to solve the problem.
SELECTION STATEMENTS
Selection Statements are used to select one alternative among the two or more available set of
statements. These conditional statements allow you to take different actions depending upon
different conditions. There are three conditional statements:
if statement, which is used when you want the script to execute if a condition is true
if...else statement, which is used when you want to execute one set of code if a condition is true
and another if it is false
switch statements, which are used when you want to select one block of code from many
depending on a situation
IF STATEMENT:
This statement is used to decide whether a block of code is to be executed or not. If the
condition is true then the code in the curly braces is executed. Here is the syntax of IF statement:
if (condition)
{
Statements
}
IF . . . ELSE STATEMENT
When you have two possible situations and you want to react differently for each, you can
use if...else statement. This means: “If the conditions specified are met, run the first block of code;
otherwise run the second block”. The syntax is as follows:
if (condition)
{
Statements
}
else
{
Statements
}
15
Example:
<html>
<head>
<title>if/else</title>
</head>
<body>
<script type=”text/javascript”>
var a,b,c;
a=10;b=20;c=30;
if(a>b)
{
if(a>c)
document.write(“a is largest number”+a);
else
} document.write(“c is largest number”+c);
else
{
if(b>c)
document.write(“b is largest number”+b);
else
} document.write(“c is largest number”+c);
</script>
</body>
</html>
SWITCH STATEMENT
A switch statement allows you to deal with several possible results of a condition. You have a
single expression. The value of this expression is then compared with the values for each case in the
structure. If there is a match, the block of code will execute.
Syntax:
switch (expression)
{
case value1: statement(s)
break;
case value2: statement(s) You use the break to prevent code from running into
break; the next case automatically.
………………….
………………….
default: statement(s)
break;
}
16
Ex:
<html>
<head>
<title>switch</title>
</head>
<body>
<script type=”text/javascript”>
var d=new Date();
ch=d.getMonth();
switch(ch)
{
case 0:document.write(“January”);
break;
case 1:document.write(“february”);
break;
case 2:document.write(“march”);
break;
case 3:document.write(“april”);
break;
case 4:document.write(“may”);
break;
case 5:document.write(“june”);
break;
case 6:document.write(“July”);
break;
case 7:document.write(“august”);
break;
case 8:document.write(“september”);
break;
case 9:document.write(“october”);
break;
case 10:document.write(“november”);
break;
case 11:document.write(“december”);
break;
default: document.write(“Invalid choice”);
}
</script>
</body>
</html>
17
A while loop that runs the same block of code while or until a condition is true.
A do while loop that runs once before the condition is checked. If the condition is true, it will
continue to run until the condition is false. The difference between while and do-while loop is
that do while runs once whether the condition is true or false.
A for loop that runs the same block of code a specified number of times
WHILE STATEMENT
In a while loop, a code block is executed repeatedly until the condition becomes false. The syntax is
as follows:
while (condition)
{
Block of statements
}
Ex:
<html>
<head>
<title>while</title>
</head>
<body>
<script type=”text/javascript”>
var i=1;
while(i<=10)
{
document.write(“Number”+i+”It‟s square”+(i*i)+”<br/>”)
i++;
}
</script>
</body>
</html>
DO . . . WHILE STATEMENT
A do ... while loop executes a block of code once and then checks a condition. As long as the
condition is true, it continues to loop. So, without evaluating the condition, the statements in the loop
runs at least once. Here is the syntax:
do
{
Statements
} while (condition);
18
Ex:
<html>
<head>
<title>do - while</title>
</head>
<body>
<script type= “text/javascript”>
var i=1;
do
{
document.write(“Number”+i+”It‟s square”+(i*i)+”<br/>”)
i++;
} while(i<=10);
</script>
</body>
</html>
FOR STATEMENT
The FOR LOOP statement executes a block of code a specified number of times. You use it
when you want to specify how many number of times body of the loop is executed.
19
BREAK STATEMENT
In general, a loop statement is terminated when the condition becomes false. The break
statement is used to break the loop forcefully even though the loop condition is true. And the break
statement is allowed to use with the conditional statement only.
Ex:
<html>
<head>
<title>break</title>
</head>
<body>
<script type=”text/javascript”>
var i;
for(i=10;i>=1;i--)
{
if(i==5)
break;
}
document.write(“My lucky Number is:”+i”)
</script>
</body>
</html>
CONTINUE STATEMENT
The continue statement is used in a loop to stop the execution of loop statements for the
current iteration and continue with the remaining iterations. And the continue statement is allowed
to use with the conditional statement only
<html>
<head>
<title>continue</title>
</head>
<body>
<script type=”text/javascript”>
var i;
for(i=10;i>=1;i--)
{
if(i==5)
{
x=i;
continue;
}
document.write(i+”<br/>”);
}
20
A function is a piece of code that performs a specific task. The function will be executed by
an event or by a call to that function. We can call a function from anywhere within the page (or even
from other pages if the function is embedded in an external .js file). JavaScript has a lot of built – in
functions.
Defining functions:
JavaScript function definition consists of the function keyword, followed by the name of the
function. A list of arguments to the function are enclosed in parentheses and separated by commas.
The statements within the function are enclosed in curly braces { }.
Syntax:
function function_name(var1,var2,...,varX)
Parameter Passing:
The parameters values that appear in a call to a function are called actual parameters. The
parameters those receives the actual parameters in the function definition when it calls are called
formal parameters.
Not every function accepts parameters. When a function receives a value as a parameter, that
value is given a name and can be accessed using that name in the function. The names of
parameters are taken from the function definition and are applied in the order in which parameters
are passed in.
The number of actual parameters in a function call is not checked against the number of
formal parameters. In function if actual parameters are excess in number then they are ignored, if the
lesser in number, then the excess formal parameters are undefined.
Primitive data types are passed by value in JavaScript. This means that a copy is made of a
variable when it is passed to a function, so any modifications made to that parameter does not affect
the original value of the variable passed.
Unlike primitive data types, composite types such as arrays and objects are passed by
reference rather than value. If references are passed then only changes made in the function affects
the actual parameters.
21
<html>
<head>
<script type="text/javascript">
function params(a,b)
{
document. writeln("<br/>No of parameters passed:"+arguments.length);
document.writeln("<br/>Parameter Values are:")
for(var i=0;i<arguments.length;i++)
22
}
return;
}
document.writeln("<br/>Parameter"+(i+1)+" "+arguments[i]);
</script>
</head>
<body>
<script type="text/javascript">
params("Ajay", "Arun");
params("Ajay","Arjun","Anand");
</script>
</body>
</html>
Output:
No of parameters
passed:2 Parameter
Values are:
Parameter1
Ajay
Parameter2
Arun
No of parameters
passed:3 Parameter
Values are:
Parameter1 Ajay
Parameter2 Arjun
Parameter3
Anand
SCOPE OF VARIABLES
The scope of a variable is the range of statements over which it is visible. When the
JavaScript is embedded in an HTML document, the scope of the variable is the range of lines of the
document over which the variable is visible.
Variables that are declared explicitly using the keyword var, inside a function have LOCAL
SCOPE and they can be allowed to access in that function only.
Variables that are declared explicitly using the keyword var, outside to all functions have
GLOBAL SCOPE and they can be allowed to access anywhere.
Variables that are not declared explicitly, and implicitly declared by JavaScript interpreter,
without using the keyword var have GLOBAL SCOPE and they are accessed anywhere in
the HTML document. Even though, if such an implicit declaration has made inside a
function, its scope is GLOBAL.
23
If a variable that is defined both as a Local Variable and Global Variable then the local
variable has more precedence, then the global variable is hidden.
JAVASCRIPT OBJECTS
In JavaScript, Objects are collection of properties, which may be either a data property or a
function or a method.
Data properties are appear in two categories: primitive values or references to other objects.
Sub programs that are called through objects are called methods.
Sub programs that are not called through objects are called functions.
All objects in a JavaScript are indirectly accessed through variables. The properties of an object
are referenced by attaching the name of the property to the variable that references the object. For
example, if car is the variable that refers an object that has the property engine, this engine
property can be accessed as car.engine.
The root object in JavaScript is Object. It is ancestor to all the objects.
A JavaScript Object can appear as a list of property – value pairs. The properties are names and
values are data values.
Properties of objects can be added or deleted at any time during execution. So they are Dynamic.
The web designer can create an object and can set its properties as per his requirements. The
object can be created using new expression. Initially the object with no properties can be set using
following statements.
obj=new Object();
Then by using dot operator we can set the properties for that object. The object can then be
modified by assigning values to that object.
Example:
<html>
<head>
<title>Object creation</title>
</head>
<body>
<script type=”text/javascript”> var
student;
student=new Object(); student.id=10;
student.name=”Vignan”;
24
document.write(“The ID is:”+student.id);
document.write(“The Name is:”+student.name);
</script>
</body>
</html>
JAVASCRIPT CONSTRUCTORS
Objects in Java Script are created using the constructors too.
Constructors are like regular functions, but we use them with the new keyword.
1. Built-in constructors such as Array and Object, which are available automatically in the
execution environment at runtime
2. Custom constructors, which define properties and methods for your own type of object.
A constructor is useful when you want to create multiple similar objects with the same properties
and methods. It’s a convention to capitalize the starting letter in the name of constructor to
distinguish them from regular functions.
function Book()
{
// unfinished code
}
var myBook = new Book();
The above line of the code creates an instance of Book and assigns it to a variable.
Although the Book constructor doesn't do anything, myBook is still an instance of it. And it is
possible to add the properties to the instance myBook dynamically. This can be illustrated in the
following example:
<html>
<body><script type= “text/javascript”>
function Book()
{
this. title= “Programming WWW”;
this. price = 500.00;
this. author= “Tim Berners Lee”;
}
var myBook = new Book(); Document.writeln(“Book
Title:”+myBook.title); Document.writeln(“Book
Author”+myBook.author);Document.writeln(“Book
Price:”+myBook.price);
25
To find out whether an object is an instance of another one, we use the instanceof operator:
myBook instanceof Book // true
myBook instanceof String // false
Note that if the right side of the instanceof operator isn‟t a function, it will throw an error:
myBook instanceof {};
// TypeError: invalid 'instanceof' operand ({})
Another way to find the type of an instance is to use the constructor property.
Consider the following code fragment:
myBook.constructor === Book; // true
The constructor property of myBook points to Book, so the strict equality operator returns
true.
STRING OBJECT
String is a set of characters enclose in a pair of single quotes or double quotes. In JavaScript
26
using string object, many useful string related functionalities can be done. Some commonly used
methods of string object are concatenating two strings, converting the string to uppercase or
lowercase, finding the substring of a given string and so on.
A String object can be declared as follows:
var str = new String(“Vignan LARA”);
PROPERTY:
Length
This property of string returns the length of the string
Example:
var str = new String(“Vignan LARA”);
str.length //gives 5
METHODS:
1. charAt(index)
This method returns the character specified by index
Example:
var str = new String(“Vignans LARA”);
str.charAt(2); // this gives the character at the index position 2 i.e. g
2. indexOf(substring [, offset])
This method returns the index of substring if found in the main string. If the substring is not found
then it returns -1. By default the indexOf( ) function starts searching the substring from index 0,
however, an optional offset may be specified, so that the search starts from that position.
Example:
var str = new String(“Vignan LARA”);
str.indexOf(“LARA”); // This gives the index position 7 as it founds the “LARA” there.
3. lastIndexOf(substring [,offset])
This method returns the index of substring if found in the main string (i.e. last occurrence). If the
substring is not found then it returns -1. By default the lastIndexOf() function starts from the last
index i.e. from backwards, however, an optional offset may be specified, so that the search starts
from that position in backwards.
Example:
var str = new String(“Vignan LARA”);
str.lastIndexOf(“LARA”);
27
Example:
“Vignan LARA”.substr(7,4);
It returns the sub string of 4 characters length from index position 7 i.e. LARA
7. toLowerCase( )
This method returns the given string converted into lower case. The original string is not altered by
this operation.
Example:
var str = new String(“Vignan LARA”);
str.toLowerCase();
8. toUpperCase( )
This method returns the given string converted into upper case. The original string is notaltered by
this operation.
Example:
var s="Vignan LARA";
s.toUpperCase();
28
9. split(separator [,limit] )
Splits the string based on the separator specified and returns that array of substrings. If the
limit is specified only those number of substrings will be returned
Example1:
var s="VLITS#LARA#GNT#AP";
var t =s.split("#");
Now, the variable t contains an array of sub strings – VLITS, LARA, GNT, AP.
MATH OBJECT
The Math Object provides a collection of properties of Number Objects and the methods that
operate on Number Objects. This Math object has methods for the trigonometric functions such as
sin, cos as well as other commonly used operations such as sqrt (), round (), floor (), ceil (), abs (),
log (), etc.
The following example rounds PI to the nearest whole number (integer) and writes it to the screen.
Example:
<html>
<head>
<title>Math object</title>
</head>
<body>
<script type=”text/javascript”>
var number=100;
document.write(“Square root of number is:”+Math.sqrt(num));
</script>
</body>
</html>
For performing the mathematical computations there are some useful methods available from math
object.
a. sqrt(num) – returns the square root of given number where num > 0
b. abs(num) – returns the absolute value of num i.e it ignores the sign of the number
c. ceil(num) – returns the integer which is equal to the smallest of the integers those are
greaterthan num.
d. floor(num) – returns the integer which is equal to the largest of the integers those are
smaller than num.
e. pow(a,b) – returns the a to the power of b value
f. min(a,b) – returns the minimum of a and b.
g. max(a,b) – returns the maximum of a and b.
h. sin(num) – returns the sine value of num.
29
The following table is the list of some of the methods of Date Object:
5. getDate() – returns the day of the month.
6. getMonth() – returns the month of the year, ranges from 0 to 11
7. getDay() – returns the day of the week ranges from 0 to 6
8. getFullYear – returns the year
9. getTime () – returns the number of milliseconds from Jan 1, 1970
10. getHours() – returns the number of hours range from 0 to 23
11. getMinutes – returns the number of minutes range from 0 to 59
12. getSeconds – returns the number of seconds range from 0 to 59
13. getMilliseconds – returns the number of milliseconds range from 0 to 999.
30
Example:
<html>
<head>
<title>Date object</title>
</head>
<body>
<script type=”text/javascript”>
var mydate=new Date();
document.write(“The Date is:”+mydate.toString()+”<br/>”);
document.write(“Today‟s Date is:”+mydate.getDate()+”<br/>”);
document.write(“Current year is:”+mydate.getFullYear()+”<br/>”);
document.write(“Minutes is:”+mydate.getMinutes()+”<br/>”);
document.write(“Seconds is:”+mydate.getSeconds()+”<br/>”);
</script>
</body>
</html>
Output:
The Date is: Fri May 07 2021 19:22:10 GMT+0530
Today Date is: 7
Current year is:
2021 Minutes is: 22
Seconds is: 10
ARRAYS
Array is a collection of similar type of elements which can be referred by a common name.
Any element in an array is referred by an array name. The particular position of an element in an
array is called “Index” or “Subscript”.
In java script the array can be created using array object.
Create an Array:
An array can be created in following ways:
1. var arrName= [“a”,”b”.”c”];
2. var arrName= new Array(3); // 3 is the size
arrName[0]= “a”;;
arrName[1]= “b”;
arrName[2]= “c”;
31
Here is a list of the methods of the Array object along with their description.
S.
Method & Description
No.
concat()
Returns a new array comprised of this array joined with other array(s) and/or value(s).
1 var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias", "Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3); // Concatenates arr1 with arr2 and arr3
indexOf()
Returns the first (least) index of an element within the array equal to the specified value, or -1 if
2 none is found.
var fruits = ["Banana", "Orange", "Apple", "Mango", "Orange"];
document.writeln(fruits.indexOf("Orange")); // it gives 1
32
lastIndexOf()
Returns the last (greatest) index of an element within the array equal to the specified value, or -1
3 if none is found.
var fruits = ["Banana", "Orange", "Apple", "Mango", "Orange"];
document.writeln(fruits.lastIndexOf("Orange")); // it gives 4
pop()
Removes the last element from an array and returns that element.
4
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from fruits
push()
Adds one or more elements to the end of an array and returns the new length of the array.
5
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits
reverse()
Reverses the order of the elements of an array -- the first becomes the last, and the last becomes
the first.
6
unshift()
Adds one or more elements to the front of an array and returns the new length of the array.
8
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits
slice()
Extracts a section of an array and returns a new array.
9
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.slice(2); // it extracts a new array starting from index 2 i.e. Apple
sort()
Sorts the elements of an array
10
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort() // it gives “Apple”, “Banana”, “Mango” , “Orange”
33
toString()
Returns a string with array elements separated by Commas
11
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.writeln(fruits.toString()); // it gives “Banana, Orange, Apple, Mango”
34
Token Description
? Match 0 or 1 time
\d Match a digit
35
Create a set of characters, one of which must match, if the operation is to be successful. If
[---] we need to specify a range of characters, then separate the first & last with Hyphen (-)
Ex: [0-9] & [D-G].
Creates a set of characters which must not match.
[^---] If any character in the set matches then operation has failed.
Ex: [^d-q]
36
Outcome:
38