JavaScript - Tutorial Basic Course
JavaScript - Tutorial Basic Course
C2 General
Table of Contents
PART 1: JAVASCRIPT BASICS ............................................................................................................................ 1
1. Overview .................................................................................................................................................. 2
What is JavaScript? .......................................................................................................................................... 2
Client-Side JavaScript....................................................................................................................................... 2
Advantages of JavaScript ................................................................................................................................. 3
Limitations of JavaScript .................................................................................................................................. 3
JavaScript Development Tools......................................................................................................................... 3
Where is JavaScript Today? ............................................................................................................................. 4
2. Syntax ....................................................................................................................................................... 5
Your First JavaScript Code ............................................................................................................................... 5
Whitespace and Line Breaks ............................................................................................................................ 6
Semicolons are Optional.................................................................................................................................. 6
Case Sensitivity ................................................................................................................................................ 7
Comments in JavaScript .................................................................................................................................. 7
3. Enabling .................................................................................................................................................... 9
JavaScript in Internet Explorer ........................................................................................................................ 9
JavaScript in Firefox ......................................................................................................................................... 9
JavaScript in Chrome ..................................................................................................................................... 10
JavaScript in Opera ........................................................................................................................................ 10
Warning for Non-JavaScript Browsers ........................................................................................................... 10
4. Placement ............................................................................................................................................... 12
JavaScript in <head>...</head> Section ......................................................................................................... 12
JavaScript in <body>...</body> Section ......................................................................................................... 13
JavaScript in <body> and <head> Sections .................................................................................................... 13
JavaScript in External File .............................................................................................................................. 14
5. Variables ................................................................................................................................................. 16
JavaScript Datatypes...................................................................................................................................... 16
JavaScript Variables ....................................................................................................................................... 16
JavaScript Variable Scope .............................................................................................................................. 17
JavaScript Variable Names............................................................................................................................. 18
JavaScript Reserved Words ........................................................................................................................... 19
6. Operators................................................................................................................................................ 20
What is an Operator? .................................................................................................................................... 20
Arithmetic Operators..................................................................................................................................... 20
Comparison Operators .................................................................................................................................. 23
Logical Operators........................................................................................................................................... 26
Bitwise Operators .......................................................................................................................................... 28
Assignment Operators ................................................................................................................................... 31
Miscellaneous Operators ............................................................................................................................... 34
7. If-Else ...................................................................................................................................................... 38
Flow Chart of if-else ....................................................................................................................................... 38
ii
if Statement ................................................................................................................................................... 39
if...else Statement ......................................................................................................................................... 40
if...else if... Statement ................................................................................................................................... 41
8. Switch-Case............................................................................................................................................. 43
Flow Chart ..................................................................................................................................................... 43
iii
17. Dialog Box ............................................................................................................................................... 94
Alert Dialog Box ............................................................................................................................................. 94
Confirmation Dialog Box ................................................................................................................................ 95
Prompt Dialog Box ......................................................................................................................................... 96
vii
Brackets ....................................................................................................................................................... 308
Quantifiers ................................................................................................................................................... 309
Literal Characters......................................................................................................................................... 310
Metacharacters ........................................................................................................................................... 311
Modifiers ..................................................................................................................................................... 311
RegExp Properties ....................................................................................................................................... 312
constructor .................................................................................................................................................. 312
global ........................................................................................................................................................... 313
ignoreCase ................................................................................................................................................... 314
lastIndex ...................................................................................................................................................... 316
multiline....................................................................................................................................................... 317
source .......................................................................................................................................................... 318
RegExp Methods .......................................................................................................................................... 319
exec ( ) ......................................................................................................................................................... 320
test ( ) .......................................................................................................................................................... 321
toSource ( ) .................................................................................................................................................. 322
toString ( ) .................................................................................................................................................. g323
viii
Part 1: JavaScript Basics
1
Javascript
1. OVERVIEW
What is JavaScript?
Javascript is a dynamic computer programming language. It is lightweight and
most commonly used as a part of web pages, whose implementations allow client-
side script to interact with the user and make dynamic pages. It is an interpreted
programming language with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java.
JavaScript made its first appearance in Netscape 2.0 in 1995 with the name
LiveScript. The general-purpose core of the language has been embedded in
Netscape, Internet Explorer, and other web browsers.
Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should
be included in or referenced by an HTML document for the code to be interpreted
by the browser.
It means that a web page need not be a static HTML, but can include programs
that interact with the user, control the browser, and dynamically create HTML
content.
The JavaScript code is executed when the user submits the form, and only if all
the entries are valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.
2
Javascript
Advantages of JavaScript
The merits of using JavaScript are:
• Less server interaction: You can validate user input before sending the
page off to the server. This saves server traffic, which means less load on
your server.
• Immediate feedback to the visitors: They don't have to wait for a page
reload to see if they have forgotten to enter something.
• Increased interactivity: You can create interfaces that react when the
user hovers over them with a mouse or activates them via the keyboard.
• Richer interfaces: You can use JavaScript to include such items as drag-
and-drop components and sliders to give a Rich Interface to your site
visitors.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features:
• Client-side JavaScript does not allow the reading or writing of files. This has
been kept for security reason.
To make our life simpler, various vendors have come up with very nice JavaScript
editing tools. Some of them are listed here:
The specification for JavaScript 2.0 can be found on the following site:
http://www.ecmascript.org/
JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within
you web page, but it is normally recommended that you should keep it within
the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text
between these tags as a script. A simple syntax of your JavaScript will appear as
follows.
<script ...>
JavaScript code
</script>
• Language: This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this attribute.
This function can be used to write text, HTML, or both. Take a look at the
following code.
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write ("Hello World!")
//-->
</script>
</body>
</html>
Hello World!
6
Javascript
But when formatted in a single line as follows, you must use semicolons:
Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords,
variables, function names, and any other identifiers must always be typed with a
consistent capitalization of letters.
So the identifiers Time and TIME will convey different meanings in JavaScript.
NOTE: Care should be taken while writing variable and function names in
JavaScript.
Comments in JavaScript
JavaScript supports both C-style and C++-style comments. Thus:
• Any text between a // and the end of a line is treated as a comment and
is ignored by JavaScript.
Example
7
Javascript
/*
* This is a multiline comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>
8
Javascript
3. ENABLING
All the modern browsers come with built-in support for JavaScript. Frequently, you
may need to enable or disable this support manually. This chapter explains the
procedure of enabling and disabling JavaScript support in your browsers: Internet
Explorer, Firefox, chrome, and Opera.
JavaScript in Firefox
Here are the steps to turn on or turn off JavaScript in Firefox:
• Open a new tab -> type about: config in the address bar.
• Then you will find the warning dialog. Select I’ll be careful, I promise!
• Then you will find the list of configure options in the browser.
• There you will find the option to enable or disable javascript by right-
clicking on the value of that option -> select toggle.
9
Javascript
JavaScript in Chrome
Here are the steps to turn on or turn off JavaScript in Chrome:
• Click the Chrome menu at the top right hand corner of your browser.
• Select Settings.
• In the "Javascript" section, select "Do not allow any site to run JavaScript"
or "Allow all sites to run JavaScript (recommended)".
JavaScript in Opera
Here are the steps to turn on or turn off JavaScript in Opera:
To disable JavaScript support in Opera, you should not select the Enable
JavaScript checkbox.
You can add a noscript block immediately after the script block as follows:
<html>
<body>
10
Javascript
<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>
Now, if the user's browser does not support JavaScript or JavaScript is not
enabled, then the message from </noscript> will be displayed on the screen.
11
Javascript
4. PLACEMENT
In the following section, we will see how we can place JavaScript in an HTML file
in different ways.
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
Click here for the result
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
Javascript
Say Hello
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
Hello World
This is web page body
<html>
<head>
<script type="text/javascript">
Javascript
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
HelloWorld
Say Hello
You are not restricted to be maintaining identical code in multiple HTML files.
The script tag provides a mechanism to allow you to store JavaScript in an
external file and then include it into your HTML files.
Here is an example to show how you can include an external JavaScript file in your
HTML code using script tag and its src attribute.
Javascript
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your
JavaScript source code in a simple text file with the extension ".js" and then
include that file as shown above.
For example, you can keep the following content in filename.js file and then
you can use sayHello function in your HTML file after including the filename.js
file.
function sayHello() {
alert("Hello World")
}
Javascript
5. VARIABLES
JavaScript Datatypes
One of the most fundamental characteristics of a programming language is the
set of data types it supports. These are the type of values that can be represented
and manipulated in a programming language.
JavaScript also defines two trivial data types, null and undefined, each of which
defines only a single value. In addition to these primitive data types, JavaScript
supports a composite data type known as object. We will cover objects in detail
in a separate chapter.
Note: Java does not make a distinction between integer values and floating- point
values. All numbers in JavaScript are represented as floating-point values.
JavaScript represents numbers using the 64-bit floating-point format defined by
the IEEE 754 standard.
JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables
can be thought of as named containers. You can place data into these containers
and then refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables
are declared with the var keyword as follows.
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
Javascript
You can also declare multiple variables with the same var keyword as follows:
<script type="text/javascript">
<!--
var money, name;
//-->
</script>
For instance, you might create a variable named money and assign the value
2000.50 to it later. For another variable, you can assign a value at the time of
initialization as follows.
<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Note: Use the var keyword only for declaration or initialization, once for the life
of any variable name in a document. You should not re-declare same variable
twice.
JavaScript is untyped language. This means that a JavaScript variable can hold
a value of any data type. Unlike many other languages, you don't have to tell
JavaScript during variable declaration what type of value the variable will hold.
The value type of a variable can change during the execution of a program and
JavaScript takes care of it automatically.
• Global Variables: A global variable has global scope which means it can
be defined anywhere in your JavaScript code.
Within the body of a function, a local variable takes precedence over a global
variable with the same name. If you declare a local variable or function parameter
with the same name as a global variable, you effectively hide the global variable.
Take a look into the following example.
<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
Local
• You should not use any of the JavaScript reserved keywords as a variable
name. These keywords are mentioned in the next section. For example,
break or boolean variable names are not valid.
• JavaScript variable names should not start with a numeral (0-9). They must
begin with a letter or an underscore character. For example,
123test is an invalid variable name but _123test is a validone.
double in super
Javascript
6. OPERATORS
What is an Operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called
operands and ‘+’ is called the operator. JavaScript supports the following types
of operators.
• Arithmetic Operators
• Comparison Operators
• Assignment Operators
Arithmetic Operators
JavaScript supports the following arithmetic operators:
+ (Addition)
- (Subtraction)
* (Multiplication)
4 / (Division)
Javascript
% (Modulus)
++ (Increment)
-- (Decrement)
Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10
will give "a10".
Example
The following code shows how to use arithmetic operators in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
Javascript
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = a++;
document.write("a++ = ");
result = a++;
document.write(result);
document.write(linebreak);
b = b--;
document.write("b-- = ");
result = b--;
document.write(result);
document.write(linebreak);
Javascript
//-->
</script>
Output
a + b = 43
a - b = 23
a / b = 3.3
a % b = 3
a + b + c = 43Test
a++ = 33
b-- = 10
Comparison Operators
JavaScript supports the following comparison operators:
== (Equal)
Checks if the value of two operands are equal or not, if yes, then
1
the condition becomes true.
!= (Not Equal)
Checks if the value of two operands are equal or not, if the values
2
are not equal, then the condition becomes true.
Ex: (A != B) is true.
Checks if the value of the left operand is less than the value of
4
the right operand, if yes, then the condition becomes true.
Checks if the value of the left operand is less than or equal to the
6 value of the right operand, if yes, then the condition becomes true.
Example
The following code shows how to use comparison operators in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
//-->
</script>
Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
(a <= b) => true
Set the variables to different values and different operators and then
try...
Logical Operators
JavaScript supports the following logical operators:
1 If both the operands are non-zero, then the condition becomes true.
|| (Logical OR)
If any of the two operands are non-zero, then the condition becomes
2
true.
Ex: (A || B) is true.
! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the
3
Logical NOT operator will make it false.
Example
Javascript
<html>
<body>
<script type="text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";
//-->
</script>
</body>
</html>
Output
Set the variables to different values and different operators and then
try...
Bitwise Operators
JavaScript supports the following bitwise operators:
Ex: (A & B) is 2.
| (BitWise OR)
Ex: (A | B) is 3.
^ (Bitwise XOR)
Ex: (A ^ B) is 1.
~ (Bitwise Not)
4 It is a unary operator and operates by reversing all the bits in the
operand.
Javascript
It moves all the bits in its first operand to the left by the number of
places specified in the second operand. New bits are filled with zeros.
5
Shifting a value left by one position is equivalent to multiplying it by 2,
shifting two positions is equivalent to multiplying by 4, and so on.
Ex: (A << 1) is 4.
Binary Right Shift Operator. The left operand’s value is moved right by
6
the number of bits specified by the right operand.
Ex: (A >> 1) is 1.
This operator is just like the >> operator, except that the bits shifted
7
in on the left are always zero.
Ex: (A >>> 1) is 1.
Example
Try the following code to implement Bitwise operator in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
//-->
</script>
Output
Javascript
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
Set the variables to different values and different operators and then
try...
Assignment Operators
JavaScript supports the following assignment operators:
= (Simple Assignment )
1 Assigns values from the right side operand to the left side operand
It adds the right operand to the left operand and assigns the result to
2
the left operand.
Ex: C += A is equivalent to C = C + A
It subtracts the right operand from the left operand and assigns the
3
result to the left operand.
Ex: C -= A is equivalent to C = C - A
It multiplies the right operand with the left operand and assigns the
4
result to the left operand.
Ex: C *= A is equivalent to C = C * A
Ex: C /= A is equivalent to C = C / A
It takes modulus using two operands and assigns the result to the left
6
operand.
Ex: C %= A is equivalent to C = C % A
Note: Same logic applies to Bitwise operators, so they will become <<=, >>=,
>>=, &=, |= and ^=.
Example
Try the following code to implement assignment operator in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";
document.write(linebreak);
//-->
</script>
Output
Set the variables to different values and different operators and then
try...
Miscellaneous Operators
We will discuss two operators here that are quite useful in JavaScript: the
conditional operator (? :) and the typeof operator.
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and
then executes one of the two given statements depending upon the result ofthe
evaluation.
? : (Conditional )
1
If Condition is true? Then value X : Otherwise value Y
Example
Try the following code to understand how the Conditional Operator works in
JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
//-->
</script>
Output
Set the variables to different values and different operators and then
try...
typeof Operator
The typeof operator is a unary operator that is placed before its single operand,
which can be of any type. Its value is a string indicating the data type of the
operand.
Number "number"
String "string"
Boolean "boolean"
Object "object"
Javascript
Function "function"
Undefined "undefined"
Null "object"
Example
The following code shows how to implement typeof operator.
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";
//-->
</script>
Output
Set the variables to different values and different operators and then
try...
Javascript
7. IF-ELSE
While writing a program, there may be a situation when you need to adopt one
out of a given set of paths. In such cases, you need to use conditional statements
that allow your program to make correct decisions and perform right actions.
• if statement
• if...else statement
38
Javascript
if Statement
The ‘if’ statement is the fundamental control statement that allows JavaScript to
make decisions and execute statements conditionally.
Syntax
The syntax for a basic if statement is as follows:
if (expression){
Statement(s) to be executed if expression is true
}
Example
Try the following example to understand how the if statement works.
<html>
<body>
<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
39
Javascript
Output
if...else Statement
The ‘if...else’ statement is the next form of control statement that allows
JavaScript to execute statements in a more controlled way.
Syntax
The syntax of an if-else statement is as follows:
if (expression){
Statement(s) to be executed if expression is true
}else{
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given
statement(s) in the ‘if’ block, are executed. If the expression is false, then the
given statement(s) in the else block are executed.
Example
Try the following code to learn how to implement an if-else statement in
JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var age = 15;
40
Javascript
//-->
</script>
Output
Syntax
The syntax of an if-else-if statement is as follows:
if (expression 1){
Statement(s) to be executed if expression 1 is true
}else if (expression 2){
Statement(s) to be executed if expression 2 is true
}else if (expression 3){
Statement(s) to be executed if expression 3 is true
}else{
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where
each if is a part of the else clause of the previous statement.Statement(s) are
executed based on the true condition, if none of the conditions is true, then the
else block is executed.
Example
41
Javascript
<html>
<body>
<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
document.write("<b>History Book</b>");
}else if( book == "maths" ){
document.write("<b>Maths Book</b>");
}else if( book == "economics" ){
document.write("<b>Economics Book</b>");
}else{
document.write("<b>Unknown Book</b>");
}
//-->
</script>
Output
Maths Book
Set the variable to different value and then try...
42
Javascript
8. SWITCH-CASE
Starting with JavaScript 1.2, you can use a switch statement which handles
exactly this situation, and it does so more efficiently than repeated if...else
if statements.
Flow Chart
The following flow chart explains a switch-case statement works.
43
Javascript
Syntax
The objective of a switch statement is to give an expression to evaluate and
several different statements to execute based on the value of the expression.
The interpreter checks each case against the value of the expression until a match
is found. If nothing matches, a default condition will be used.
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted,
the interpreter would continue executing each statement in each of the following
cases.
Example
<html>
<body>
<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("Good job<br />");
44
Javascript
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;
case 'F': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
Output
Break statements play a major role in switch-case statements. Try the following
code that uses switch-case statement without any break statement.
<html>
<body>
<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
45
Javascript
switch (grade)
{
case 'A': document.write("Good job<br />");
case 'B': document.write("Pretty good<br />");
case 'C': document.write("Passed<br />");
case 'D': document.write("Not so good<br />");
case 'F': document.write("Failed<br />");
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
Output
46
Javascript
9. WHILE LOOP
While writing a program, you may encounter a situation where you need to
perform an action over and over again. In such situations, you would need to write
loop statements to reduce the number of lines.
JavaScript supports all the necessary loops to ease down the pressure of
programming.
Flow Chart
The flow chart of while loop looks as follows:
47
Javascript
Syntax
while (expression){
Statement(s) to be executed if expression is true
}
Example
<html>
<body>
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop ");
while (count < 10){
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");
//-->
</script>
Output
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...
Flow Chart
The flow chart of a do-while loop would be as follows:
do{
conditional code;
}while(condition);
Conditional
Code
Condition
If condition is
true
If Condition
is false
Syntax
The syntax for do-while loop in JavaScript is as follows:
Javascript
do{
Statement(s) to be executed;
} while (expression);
Note: Don’t miss the semicolon used at the end of the do...while loop.
Example
Try the following example to learn how to implement a do-while loop in
JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
do{
document.write("Current Count : " + count + "<br />");
count++;
}while (count < 5);
document.write ("Loop stopped!");
//-->
</script>
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop Stopped!
Javascript
• The test statement which will test if a given condition is true or not. If the
condition is true, then the code given inside the loop will be executed,
otherwise the control will come out of the loop.
You can put all the three parts in a single line separated by semicolons.
Flow Chart
The flow chart of a for loop in JavaScript would be as follows:
Conditional
Code
Condition
for condition
is true
for Condition
is false
Javascript
Syntax
The syntax of for loop is JavaScript is as follows:
Example
Try the following example to learn how a for loop works in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++){
document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Javascript
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...
Javascript
11. FOR-IN LOOP
The for...in loop is used to loop through an object's properties. As we have not
discussed Objects yet, you may not feel comfortable with this loop. But once you
understand how objects behave in JavaScript, you will find this loop very useful.
Syntax
The syntax of ‘for..in’ loop is:
Example
Try the following example to implement ‘for-in’ loop. It prints the web browser’s
Navigator object.
<html>
<body>
<script type="text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator)
{
document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
//-->
</script>
Javascript
Output
JavaScript provides full control to handle loops and switch statements. There
may be a situation when you need to come out of a loop without reaching at its
bottom. There may also be a situation when you want to skip a part of your code
block and start the next iteration of the look.
Flow Chart
The flow chart of a break statement would look as follows:
Conditional Code
Condition true
Break
statement
false
Example
The following example illustrates the use of a break statement with a while loop.
Notice how the loop breaks out early once x reaches 5 and reaches to
document.write (..) statement just below to the closing curly brace:
57
Javascript
<html>
<body>
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20)
{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
Output
We have already seen the usage of break statement inside a switch statement.
58
Javascript
Example
This example illustrates the use of a continue statement with a while loop. Notice
how the continue statement is used to skip printing when the index held in
variable x reaches 5.
<html>
<body>
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10)
{
x = x + 1;
if (x == 5){
continue; // skill rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
Output
59
Javascript
Note: Line breaks are not allowed between the ‘continue’ or ‘break’ statement
and its label name. Also, there should not be any other statement in between a
label name and associated loop.
Example 1
The following example shows how to implement Label with a break statement.
<html>
<body>
<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 5; i++)
{
document.write("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++)
60
Javascript
{
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer loop
document.write("Innerloop: " + j + " <br />");
}
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
</body>
</html>
Output
Example 2
The following example shows how to implement Label with continue.
<html>
61
Javascript
<body>
<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 3; i++)
{
document.write("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++)
{
if (j == 3){
continue outerloop;
}
document.write("Innerloop: " + j + "<br />");
}
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
</body>
</html>
Output
62
Javascript
Innerloop: 2
Exiting the loop!
63
Javascript
13. FUNCTIONS
Like any other advanced programming language, JavaScript also supports all the
features necessary to write modular code using functions. You must have seen
functions like alert() and write() in the earlier chapters. We were using these
functions again and again, but they had been written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section explains
how to write your own functions in JavaScript.
Function Definition
Before we use a function, we need to define it. The most common way to define
a function in JavaScript is by using the function keyword, followed by a unique
function name, a list of parameters (that might be empty), and a statement
block surrounded by curly braces.
Syntax
The basic syntax is shown here.
<script type="text/javascript">
<!--
function functionname(parameter-list)
{
statements
}
//-->
</script>
Example
Try the following example. It defines a function called sayHello that takes no
parameters:
Javascript
<script type="text/javascript">
<!--
function sayHello()
{
alert("Hello there");
}
//-->
</script>
Calling a Function
To invoke a function somewhere later in the script, you would simply need to
write the name of that function as shown in the following code.
<html>
<head>
<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
Output
Javascript
Say Hello
Function Parameters
Till now, we have seen functions without parameters. But there is a facility to pass
different parameters while calling a function. These passed parameters can be
captured inside the function and any manipulation can be done over those
parameters. A function can take multiple parameters separated by comma.
Example
Try the following example. We have modified our sayHello function here. Now it
takes two parameters.
<html>
<head>
<script type="text/javascript">
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('Zara', 7)" value="Say Hello">
</form>
Output
Say Hello
For example, you can pass two numbers in a function and then you can expect
the function to return their multiplication in your calling program.
Example
Try the following example. It defines a function that takes two parameters and
concatenates them before returning the resultant in the calling program.
<html>
<head>
<script type="text/javascript">
function concatenate(first, last)
{
var full;
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
Output
There is a lot to learn about JavaScript functions, however we have covered the
most important concepts in this tutorial.
Nested Functions
Prior to JavaScript 1.2, function definition was allowed only in top level global
code, but JavaScript 1.2 allows function definitions to be nested within other
functions as well. Still there is a restriction that function definitions may not appear
within loops or conditionals. These restrictions on function definitions apply only
to function declarations with the function statement.
As we'll discuss later in the next chapter, function literals (another feature
introduced in JavaScript 1.2) may appear within any JavaScript expression,
which means that they can appear within if and other statements.
Example
Try the following example to learn how to implement nested functions.
<html>
Javascript
<head>
<script type="text/javascript">
<!--
function hypotenuse(a, b) {
function square(x) { return x*x; }
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
Output
Call Function
Javascript
Function () Constructor
The function statement is not the only way to define a new function; you can
define your function dynamically using Function() constructor along with the
new operator.
Syntax
Following is the syntax to create a function using Function() constructor along
with the new operator.
<script type="text/javascript">
<!--
var variablename = new Function(Arg1, Arg2..., "Function Body");
//-->
</script>
The Function() constructor expects any number of string arguments. The last
argument is the body of the function – it can contain arbitrary JavaScript
statements, separated from each other by semicolons.
Notice that the Function() constructor is not passed any argument that specifies
a name for the function it creates. The unnamed functions created with the
Function() constructor are called anonymous functions.
Example
Try the following example.
<html>
<head>
<script type="text/javascript">
<!--
var func = new Function("x", "y", "return x*y;");
function secondFunction(){
var result;
result = func(10,20);
Javascript
document.write ( result );
}
//-->
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
Output
Function Literals
JavaScript 1.2 introduces the concept of function literals which is another new
way of defining functions. A function literal is an expression that defines an
unnamed function.
Syntax
The syntax for a function literal is much like a function statement, except that
it is used as an expression rather than a statement and no function name is
required.
<script type="text/javascript">
<!--
Javascript
Syntactically, you can specify a function name while creating a literal function as
follows.
<script type="text/javascript">
<!--
var variablename = function FunctionName(Argument List){
Function Body
};
//-->
</script>
But this name does not have any significance, so it is not worthwhile.
Example
Try the following example. It shows the usage of function literals.
<html>
<head>
<script type="text/javascript">
<!--
var func = function(x,y){ return x*y };
function secondFunction(){
var result;
result = func(10,20);
document.write ( result );
}
//-->
</script>
</head>
<body>
Javascript
Output
Call Function
What is an Event?
JavaScript's interaction with HTML is handled through events that occur when
the user or the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that
click too is an event. Other examples include events like pressing any key, closing
a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which
cause buttons to close windows, messages to be displayed to users, data to be
validated, and virtually any other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.
Please go through this small tutorial for a better understanding HTML Event
Reference. Here we will see a few examples to understand the relation between
Event and JavaScript.
Example
Try the following example.
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
document.write ("Hello World")
}
//-->
</script>
Javascript
</head>
<body>
<p> Click the following button and see result</p>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
Output
Example
The following example shows how to use onsubmit. Here we are callinga
validate() function before submitting a form data to the webserver. If
validate() function returns true, the form will be submitted, otherwise it will not
submit the data.
<html>
<head>
<script type="text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
75
Javascript
<body>
<form method="POST" action="t.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>
<html>
<head>
<script type="text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
76
Javascript
Output
oncanplay script Triggers when media can start play, but might
has to stop for buffering
77
Javascript
78
Javascript
79
Javascript
80
Javascript
81
Javascript
15. COOKIES
How It Works?
Your server sends some data to the visitor's browser in the form of a cookie. The
browser may accept the cookie. If it does, it is stored as a plain text record on the
visitor's hard drive. Now, when the visitor arrives at another page on your site,
the browser sends the same cookie to the server for retrieval. Onceretrieved, your
server knows/remembers what was stored earlier.
• Expires: The date the cookie will expire. If this is blank, the cookie will
expire when the visitor quits the browser.
• Path: The path to the directory or web page that set the cookie. This may
be blank if you want to retrieve the cookie from any directory or page.
• Secure: If this field contains the word "secure", then the cookie may only
be retrieved with a secure server. If this field is blank, no such restriction
exists.
• Name=Value: Cookies are set and retrieved in the form of key-value pairs.
Cookies were originally designed for CGI programming. The data contained in a
cookie is automatically transmitted between the web browser and the web
server, so CGI scripts on the server can read and write cookie values that are
stored on the client.
82
Javascript
JavaScript can also manipulate cookies using the cookie property ofthe
Document object. JavaScript can read, create, modify, and delete the cookies
that apply to the current web page.
Storing Cookies
The simplest way to create a cookie is to assign a string value to the
document.cookie object, which looks like this.
document.cookie = "key1=value1;key2=value2;expires=date";
Here the expires attribute is optional. If you provide this attribute with a valid
date or time, then the cookie will expire on a given date or time and thereafter,
the cookies' value will not be accessible.
Note: Cookie values may not include semicolons, commas, or whitespace. For this
reason, you may want to use the JavaScript escape() function to encodethe
value before storing it in the cookie. If you do this, you will also have to use the
corresponding unescape() function when you read the cookie value.
Example
Try the following. It sets a customer name in an input cookie.
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
if( document.myform.customer.value == "" ){
alert ("Enter some value!");
return;
}
83
Javascript
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
</body>
</html>
Output
Now your machine has a cookie called name. You can set multiple cookies using
multiple key=value pairs separated by comma.
Reading Cookies
Reading a cookie is just as simple as writing one, because the value of the
document.cookie object is the cookie. So you can use this string whenever you
want to access the cookie. The document.cookie string will keep a listof
name=value pairs separated by semicolons, where name is the name of a cookie
and value is its string value.
You can use strings' split() function to break a string into key and values as
follows:
Example
Try the following example to get all the cookies.
<html>
<head>
<script type="text/javascript">
<!--
function ReadCookie()
{
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
84
Javascript
Note: Here length is a method of Array class which returns the length of an
array. We will discuss Arrays in a separate chapter. By that time, please try to
digest it.
Output
Get Cookie
Note: There may be some other cookies already set on your machine. The
above code will display all the cookies set on your machine.
85
Javascript
Example
Try the following example. It illustrates how to extend the expiry date of a cookie
by 1 Month.
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
86
Javascript
Output
Deleting a Cookie
Sometimes you will want to delete a cookie so that subsequent attempts to read
the cookie return nothing. To do this, you just need to set the expiry date to a
time in the past.
Example
Try the following example. It illustrates how to delete a cookie by setting its expiry
date to one month behind the current date.
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
87
Javascript
</body>
</html>
Output
Set Cookie
Enter Cookie Name:
88
Javascript
16. PAGE REDIRECT
There could be various reasons why you would like to redirect a user from the
original page. We are listing down a few of the reasons:
• You did not like the name of your domain and you are moving to a new one.
In such a scenario, you may want to direct all your visitors to the new site.
Here you can maintain your old domain but put a single page with a page
redirection such that all your old domain visitors can come to your new
domain.
• The Search Engines may have already indexed your pages. But while
moving to another domain, you would not like to lose your visitors coming
through search engines. So you can use client-side page redirection. But
keep in mind this should not be done to fool the search engine, it could lead
your site to get banned.
Auto Refresh
You can also use JavaScript to refresh the page automatically after a given time
period. Here setTimeout() is a built-in JavaScript function which can be used to
execute another function after a given time interval.
89
Javascript
Example
Try the following example. It shows how to refresh a page after every 5
seconds. You can change this time as per your requirement.
<html>
<head>
<script type="text/JavaScript">
<!--
function AutoRefresh( t ) {
setTimeout("location.reload(true);", t);
}
// -->
</script>
</head>
<body onload="JavaScript:AutoRefresh(5000);">
<p>This page will refresh every 5 seconds.</p>
</body>
</html>
Output
Example 1
It is quite simple to do a page redirect using JavaScript at client side. To redirect
your site visitors to a new page, you just need to add a line in your head section
as follows.
<html>
<head>
<script type="text/javascript">
<!--
function Redirect() {
90
Javascript
window.location="http://www.tutorialspoint.com";
}
//-->
</script>
</head>
<body>
<p>Click the following button, you will be redirected to home page.</p>
<form>
<input type="button" value="Redirect Me" onclick="Redirect();" />
</form>
</body>
</html>
Output
Example 2
You can show an appropriate message to your site visitors before redirecting them
to a new page. This would need a bit time delay to load a new page. The following
example shows how to implement the same. Here setTimeout() is a built-in
JavaScript function which can be used to execute another function aftera given
time interval.
<html>
<head>
<script type="text/javascript">
<!--
function Redirect() {
window.location="http://www.tutorialspoint.com";
}
document.write ("You will be redirected to our main page in 10
seconds!");
91
Javascript
setTimeout('Redirect()', 10000);
//-->
</script>
</head>
<body>
</body>
</html>
Output
Example 3
The following example shows how to redirect your site visitors onto a different
page based on their browsers.
<html>
<head>
<script type="text/javascript">
<!--
var browsername=navigator.appName;
if( browsername == "Netscape" )
{
window.location="http://www.location.com/ns.htm";
}
else if ( browsername =="Microsoft Internet Explorer")
{
window.location="http://www.location.com/ie.htm";
}
else
{
window.location="http://www.location.com/other.htm";
}
//-->
</script>
92
Javascript
</head>
<body>
</body>
</html>
93
Javascript
17. DIALOG BOX
JavaScript supports three important types of dialog boxes. These dialog boxes can
be used to raise and alert, or to get confirmation on any input or to have a kind
of input from the users. Here we will discuss each dialog box one by one.
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives
only one button "OK" to select and proceed.
Example
<html>
<head>
<script type="text/javascript">
<!--
function Warn() {
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="Warn();" />
</form>
</body>
</html>
94
Javascript
Output
Click Me
If the user clicks on the OK button, the window method confirm() will return true.
If the user clicks on the Cancel button, then confirm() returns false. You can use
a confirmation dialog box as follows.
Example
<html>
<head>
<script type="text/javascript">
<!--
function getConfirmation(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
document.write ("User wants to continue!");
return true;
}else{
Document.write ("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
95
Javascript
Output
This dialog box is displayed using a method called prompt() which takes two
parameters: (i) a label which you want to display in the text box and (ii) a default
string to display in the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button,
the window method prompt() will return the entered value from thetext box.
If the user clicks the Cancel button, the window method prompt()
returns null.
Example
The following example shows how to use a prompt dialog box:
<html>
<head>
<script type="text/javascript">
<!--
function getValue(){
var retVal = prompt("Enter your name : ", "your name here");
96
Javascript
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</form>
</body>
</html>
Output
97
Javascript
18. VOID KEYWORD
Syntax
The syntax of void can be either of the following two:
<head>
<script type="text/javascript">
<!--
void func()
javascript:void func()
OR
void(func())
javascript:void(func())
//-->
</script>
</head>
Example 1
The most common use of this operator is in a client-side javascript: URL, where
it allows you to evaluate an expression for its side-effects without the browser
displaying the value of the evaluated expression.
Here the expression alert ('Warning!!!') is evaluated but it is not loaded back
into the current document:
<html>
<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
98
Javascript
<body>
<p>Click the following, This won't react at all...</p>
<a href="javascript:void(document.write(“Hello : 0”))">Click me!</a>
</body>
</html>
Output
Example 2
Take a look at the following example. The following link does nothing because
the expression "0" has no effect in JavaScript. Here the expression "0" is
evaluated, but it is not loaded back into the current document.
<html>
<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<p>Click the following, This won't react at all...</p>
<a href="javascript:void(0)">Click me!</a>
</body>
</html>
Output
Example 3
Another use of void is to purposely generate the undefined value as follows.
<html>
99
Javascript
<head>
<script type="text/javascript">
<!--
function getValue(){
var a,b,c;
a = void ( b = 5, c = 7 );
document.write('a = ' + a + ' b = ' + b +' c = ' + c );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</body>
</html>
Output
Click Me
100
Javascript
19. PAGE PRINTING
Many times you would like to place a button on your webpage to print the content
of that web page via an actual printer. JavaScript helps you to implement this
functionality using the print function of window object.
The JavaScript print function window.print() prints the current web page when
executed. You can call this function directly using the onclick event as shown in
the following example.
Example
Try the following example.
<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<form>
<input type="button" value="Print" onclick="window.print()" />
</form>
</body>
Output
1. Make a copy of the page and leave out unwanted text and graphics, then
link to that printer friendly page from the original. Check Example.
Javascript
2. If you do not want to keep an extra copy of a page, then you can mark
your printable text using proper comments like <!-- PRINT STARTS HERE
-->..... <!-- PRINT ENDS HERE --> and then you can use PERL or any other
script in the background to purge printable text and display for final
printing. We at Tutorialspoint use this method to provide print facility to our
site visitors. Check Example.
Object Properties
Object properties can be any of the three primitive data types, or any of the
abstract data types, such as another object. Object properties are usuallyvariables
that are used internally in the object's methods, but can also be globally visible
variables that are used throughout the page.
objectName.objectProperty = propertyValue;
For example: The following code gets the document title using the "title"
property of the document object.
Object Methods
Methods are the functions that let the object do something or let something be
done to it. There is a small difference between a function and a method – at a
function is a standalone unit of statements and a method is attached to an object
and can be referenced by the this keyword.
Javascript
Methods are useful for everything from displaying the contents of the object to
the screen to performing complex mathematical operations on a group of local
properties and parameters.
User-Defined Objects
All user-defined objects and built-in objects are descendants of an object called
Object.
In the following example, the constructor methods are Object(), Array(), and
Date(). These constructors are built-in JavaScript functions.
The variable contains a reference to the new object. The properties assigned to
the object are not variables and are not defined with the var keyword.
Example 1
Try the following example; it demonstrates how to create an Object.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
Javascript
book.author = "Mohtashim";
</script>
</head>
<body>
<script type="text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
Output
Example 2
This example demonstrates how to create an object with a User-Defined Function.
Here this keyword is used to refer to the object that has been passed to a function.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
Javascript
</script>
</body>
</html>
Output
Example
Try the following example; it shows how to add a function along with an object.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
</script>
</head>
<body>
Javascript
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
Output
The ‘with’Keyword
The ‘with’ keyword is used as a kind of shorthand for referencing an object's
properties or methods.
The object specified as an argument to with becomes the default object for the
duration of the block that follows. The properties and methods for the object can
be used without naming the object.
Syntax
The syntax for with object is as follows:
with (object){
properties used without the object name and dot
}
Example
<html>
Javascript
<head>
<title>User-defined objects</title>
<script type="text/javascript">
Output
Syntax
The syntax for creating a number object is as follows:
In the place of number, if you provide any non-number argument, then the
argument cannot be converted into a number, it returns NaN (Not-a-Number).
Number Properties
Here is a list of each property and their description.
Property Description
MAX_VALUE
The Number.MAX_VALUE property belongs to the static Number object. It
represents constants for the largest possible positive numbers that JavaScript can
work with.
Syntax
Example
<html>
<head>
<script type="text/javascript">
<!--
function showValue()
{
var val = Number.MAX_VALUE;
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="showValue();" />
Javascript
</form>
</body>
</html>
Output
MIN_VALUE
The Number.MIN_VALUE property belongs to the static Number object. It
represents constants for the smallest possible positive numbers that JavaScript
can work with.
Syntax
The syntax to use MIN_VALUE is:
Example
<html>
<head>
<script type="text/javascript">
<!--
function showValue()
{
var val = Number.MIN_VALUE;
alert("Value of Number.MIN_VALUE : " + val );
}
//-->
Javascript
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="showValue();" />
</form>
</body>
</html>
Output
NaN
Unquoted literal constant NaN is a special value representing Not-a-Number. Since
NaN always compares unequal to any number, including NaN, it is usually used to
indicate an error condition for a function that should return a valid number.
Note: Use the isNaN() global function to see if a value is an NaN value.
Syntax
The syntax to use NaN is:
Example
<html>
Javascript
<head>
<script type="text/javascript">
<!--
function showValue()
{
var dayOfMonth = 50;
if (dayOfMonth < 1 || dayOfMonth > 31)
{
dayOfMonth = Number.NaN
alert("Day of Month must be between 1 and 31.")
}
Document.write("Value of dayOfMonth : " + dayOfMonth );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="showValue();" />
</form>
</body>
</html>
Output
Click Me
Javascript
NEGATIVE_INFINITY
This is a special numeric value representing a value less than
Number.MIN_VALUE. This value is represented as "-Infinity". It resembles an
infinity in its mathematical behavior. For example, anything multiplied by
NEGATIVE_INFINITY is NEGATIVE_INFINITY, and anything divided by
NEGATIVE_INFINITY is zero.
Syntax
The syntax to use NEGATIVE_INFINITY is as follows:
Example
<html>
<head>
<script type="text/javascript">
<!--
function showValue()
{
var smallNumber = (-Number.MAX_VALUE) * 2
if (smallNumber == Number.NEGATIVE_INFINITY) {
alert("Value of smallNumber : " + smallNumber );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
Javascript
Output
POSITIVE_INFINITY
This is a special numeric value representing any value greater than
Number.MAX_VALUE. This value is represented as "Infinity". It resembles an
infinity in its mathematical behavior. For example, anything multiplied by
POSITIVE_INFINITY is POSITIVE_INFINITY, and anything divided by
POSITIVE_INFINITY is zero.
Syntax
Use the following syntax to use POSITIVE_INFINITY.
Example
<html>
<head>
<script type="text/javascript">
<!--
function showValue()
{
var bigNumber = Number.MAX_VALUE * 2
if (bigNumber == Number.POSITIVE_INFINITY) {
Javascript
Output
Prototype
The prototype property allows you to add properties and methods to any object
(Number, Boolean, String and Date etc.).
Note: Prototype is a global property which is available with almost all the
objects.
Syntax
Use the following syntax to use Prototype.
object.prototype.name = value
Example
Javascript
Try the following example to use the prototype property to add a property to an
object.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
Output
constructor
It returns a reference to the Number function that created the instance's
prototype.
Syntax
Its syntax is as follows:
number.constructor()
Return value
Returns the function that created this object's instance.
Example
Try the following example.
<html>
<head>
<title>JavaScript constructor() Method</title>
</head>
<body>
<script type="text/javascript">
var num = new Number( 177.1234 );
document.write("num.constructor() is : " + num.constructor);
</script>
</body>
</html>
Output
Number Methods
The Number object contains only the default methods that are a part of every
object's definition.
Method Description
toPrecision() Defines how many total digits (including digits to the left and
right of the decimal) to display of a number.
In the following sections, we will have a few examples to explain the methods of
Number.
toExponential ()
This method returns a string representing the number object in exponential
notation.
Syntax
Its syntax is as follows:
number.toExponential( [fractionDigits] )
Parameter Details
fractionDigits: An integer specifying the number of digits after the decimal point.
Defaults to as many digits as necessary to specify the number.
Return Value
A string representing a Number object in exponential notation with one digit before
the decimal point, rounded to fractionDigits digits after the decimal point. If the
fractionDigits argument is omitted, the number of digits after the decimal point
defaults to the number of digits necessary to represent the value uniquely.
Example
Javascript
<html>
<head>
<title>Javascript Method toExponential()</title>
</head>
<body>
<script type="text/javascript">
var num=77.1234;
var val = num.toExponential();
document.write("num.toExponential() is : " + val );
document.write("<br />");
val = num.toExponential(4);
document.write("num.toExponential(4) is : " + val );
document.write("<br />");
val = num.toExponential(2);
document.write("num.toExponential(2) is : " + val);
document.write("<br />");
val = 77.1234.toExponential();
document.write("77.1234.toExponential()is : " + val );
document.write("<br />");
val = 77.1234.toExponential();
document.write("77 .toExponential() is : " + val);
</script>
</body>
</html>
Output
num.toExponential() is : 7.71234e+1
num.toExponential(4) is : 7.7123e+1
Javascript
num.toExponential(2) is : 7.71e+1
77.1234.toExponential()is : 7.71234e+1
77 .toExponential() is : 7.71234e+1
toFixed ()
This method formats a number with a specific number of digits to the right of
the decimal.
Syntax
Its syntax is as follows:
number.toFixed( [digits] )
Parameter Details
digits: The number of digits to appear after the decimal point.
Return Value
A string representation of number that does not use exponential notation and
has the exact number of digits after the decimal place.
Example
Try the following example.
<html>
<head>
<title>JavaScript toFixed() Method</title>
</head>
<body>
<script type="text/javascript">
var num=177.1234;
document.write("num.toFixed() is : " + num.toFixed());
document.write("<br />");
document.write("num.toFixed(6) is : " + num.toFixed(6));
document.write("<br />");
document.write("num.toFixed(1) is : " + num.toFixed(1));
document.write("<br />");
document.write("(1.23e+20).toFixed(2) is:" +
(1.23e+20).toFixed(2));
Javascript
document.write("<br />");
document.write("(1.23e-10).toFixed(2) is : " +
(1.23e-10).toFixed(2));
</script>
</body>
</html>
Output
num.toFixed() is : 177
num.toFixed(6) is : 177.123400
num.toFixed(1) is : 177.1
(1.23e+20).toFixed(2) is:123000000000000000000.00
(1.23e-10).toFixed(2) is : 0.00
toLocaleString ()
This method converts a number object into a human readable string
representing the number using the locale of the environment.
Syntax
Its syntax is as follows:
number.toLocaleString()
Return Value
Returns a human readable string representing the number using the locale of
the environment.
Example
Try the following example.
<html>
<head>
<title>JavaScript toLocaleString() Method </title>
</head>
<body>
<script type="text/javascript">
Javascript
Output
177.123
toPrecision ()
This method returns a string representing the number object to the specified
precision.
Syntax
Its syntax is as follows:
number.toPrecision( [ precision ] )
Parameter Details
precision: An integer specifying the number of significant digits.
Return Value
Returns a string representing a Number object in fixed-point or exponential
notation rounded toprecision significant digits.
Example
Try the following example.
<html>
<head>
<title>JavaScript toPrecision() Method </title>
</head>
<body>
<script type="text/javascript">
var num = new Number(7.123456);
Javascript
Output
num.toPrecision() is 7.123456
num.toPrecision(4) is 7.123
num.toPrecision(2) is 7.1
num.toPrecision(1) is 7
toString ()
This method returns a string representing the specified object. The toString()
method parses its first argument, and attempts to return a string representation
in the specified radix (base).
Syntax
Its syntax is as follows:
number.toString( [radix] )
Parameter Details
radix: An integer between 2 and 36 specifying the base to use for representing
numeric values.
Return Value
Returns a string representing the specified Number object.
Example
Javascript
<html>
<head>
<title>JavaScript toString() Method </title>
</head>
<body>
<script type="text/javascript">
var num = new Number(15);
document.write("num.toString() is " + num.toString());
document.write("<br />");
Output
num.toString() is 15
num.toString(2) is 1111
num.toString(4) is 33
valueOf ()
This method returns the primitive value of the specified number object.
Syntax
Its syntax is as follows:
number.valueOf()
Return Value
Javascript
Example
Try the following example.
<html>
<head>
<title>JavaScript valueOf() Method </title>
</head>
<body>
<script type="text/javascript">
var num = new Number(15.11234);
document.write("num.valueOf() is " + num.valueOf());
</script>
</body>
</html>
Output
num.valueOf() is 15.11234
Javascript
22. BOOLEAN
Syntax
Boolean Properties
Here is a list of the properties of Boolean object:
Property Description
In the following sections, we will have a few examples to illustrate the properties
of Boolean object.
constructor ()
Javascript boolean constructor() method returns a reference to the Boolean
function that created the instance's prototype.
Syntax
Use the following syntax to create a Boolean constructor() method.
boolean.constructor()
Return Value
Javascript
Example
Try the following example.
<html>
<head>
<title>JavaScript constructor() Method</title>
</head>
<body>
<script type="text/javascript">
var bool = new Boolean( );
document.write("bool.constructor() is : " + bool.constructor);
</script>
</body>
</html>
Output
Prototype
The prototype property allows you to add properties and methods to any object
(Number, Boolean, String and Date, etc.).
Note: Prototype is a global property which is available with almost all the
objects.
Syntax
Use the following syntax to create a Boolean prototype.
object.prototype.name = value
Example
Javascript
Try the following example; it shows how to use the prototype property to add a
property to an object.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
Output
Boolean Methods
Here is a list of the methods of Boolean object and their description.
Javascript
Method Description
In the following sections, we will have a few examples to demonstrate the usage
of the Boolean methods.
toSource ()
Javascript boolean toSource() method returns a string representing the source
code of the object.
Syntax
Its syntax is as follows:
boolean.toSource()
Return Value
Returns a string representing the source code of the object.
Example
Try the following example.
<html>
<head>
<title>JavaScript toSource() Method</title>
</head>
<body>
<script type="text/javascript">
function book(title, publisher, price)
{
Javascript
this.title = title;
this.publisher = publisher;
this.price = price;
}
var newBook = new book("Perl","Leo Inc",200);
document.write("newBook.toSource() is : "+ newBook.toSource());
</script>
</body>
</html>
Output
toString ()
This method returns a string of either "true" or "false" depending upon the value
of the object.
Syntax
Its syntax is as follows:
boolean.toString()
Return Value
Returns a string representing the specified Boolean object.
Example
Try the following example.
<html>
<head>
<title>JavaScript toString() Method</title>
</head>
<body>
<script type="text/javascript">
var flag = new Boolean(false);
document.write( "flag.toString is : " + flag.toString() );
Javascript
</script>
</body>
</html>
Output
flag.toString is : false
valueOf ()
Javascript boolean valueOf() method returns the primitive value of the
specified boolean object.
Syntax
Its syntax is as follows:
boolean.valueOf()
Return Value
Returns the primitive value of the specified boolean object.
Example
Try the following example.
<html>
<head>
<title>JavaScript toString() Method</title>
</head>
<body>
<script type="text/javascript">
var flag = new Boolean(false);
document.write( "flag.valueOf is : " + flag.valueOf() );
</script>
</body>
</html>
Output
flag.valueOf is : false
Javascript
Javascript
23. STRING
The String object lets you work with a series of characters; it wraps Javascript's
string primitive data type with a number of helper methods.
Syntax
Use the following syntax to create a String object:
The string parameter is a series of characters that has been properly encoded.
String Properties
Here is a list of the properties of String object and their description.
Property Description
In the following sections, we will have a few examples to demonstrate the usage
of String properties.
constructor
A constructor returns a reference to the string function that created the
instance's prototype.
Javascript
Syntax
Its syntax is as follows:
string.constructor
Return Value
Returns the function that created this object's instance.
Example
Try the following example.
<html>
<head>
<title>JavaScript String constructor property</title>
</head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
document.write("str.constructor is:" + str.constructor);
</script>
</body>
</html>
Output
Length
This property returns the number of characters in a string.
Syntax
Use the following syntax to find the length of a string:
string.length
Return Value
Returns the number of characters in the string.
Example
Javascript
<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
document.write("str.length is:" + str.length);
</script>
</body>
</html>
Output
str.length is:14
Prototype
The prototype property allows you to add properties and methods to any object
(Number, Boolean, String, Date, etc.).
Note: Prototype is a global property which is available with almost all the
objects.
Syntax
Its syntax is as follows:
object.prototype.name = value
Example
Try the following example.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
Javascript
Output
String Methods
Here is a list of the methods available in String object along with their
description.
Method Description
indexOf() Returns the index within the calling String object of the
first occurrence of the specified value, or -1 if not found.
lastIndexOf() Returns the index within the calling String object of the
last occurrence of the specified value, or -1 if not found.
In the following sections, we will have a few examples to demonstrate the usage
of String methods.
charAt()
charAt() is a method that returns the character from the specified index.
Characters in a string are indexed from left to right. The index of the first character
is 0, and the index of the last character in a string, called stringName, is
stringName.length – 1.
Syntax
Use the following syntax to find the character at a particular index.
string.charAt(index)
Argument Details
index: An integer between 0 and 1 less than the length of the string.
Return Value
Returns the character from the specified index.
Example
Try the following example.
<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
document.writeln("str.charAt(0) is:" + str.charAt(0));
document.writeln("<br />str.charAt(1) is:" + str.charAt(1));
document.writeln("<br />str.charAt(2) is:" + str.charAt(2));
Javascript
Output
str.charAt(0) is:T
str.charAt(1) is:h
str.charAt(2) is:i
str.charAt(3) is:s
str.charAt(4) is:
str.charAt(5) is:i
charCodeAt ()
This method returns a number indicating the Unicode value of the character at the
given index.
Unicode code points range from 0 to 1,114,111. The first 128 Unicode code points
are a direct match of the ASCII character encoding. charCodeAt() always
returns a value that is less than 65,536.
Syntax
Use the following syntax to find the character code at a particular index.
string.charCodeAt(index)
Argument Details
index: An integer between 0 and 1 less than the length of the string; ifunspecified,
defaults to 0.
Return Value
Returns a number indicating the Unicode value of the character at the given index.
It returns NaN if the given index is not between 0 and 1 less than the length of
the string.
Example
Javascript
<html>
<head>
<title>JavaScript String charCodeAt() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
document.write("str.charCodeAt(0) is:" + str.charCodeAt(0));
document.write("<br />str.charCodeAt(1) is:" + str.charCodeAt(1));
document.write("<br />str.charCodeAt(2) is:" + str.charCodeAt(2));
document.write("<br />str.charCodeAt(3) is:" + str.charCodeAt(3));
document.write("<br />str.charCodeAt(4) is:" + str.charCodeAt(4));
document.write("<br />str.charCodeAt(5) is:" + str.charCodeAt(5));
</script>
</body>
</html>
Output
str.charCodeAt(0) is:84
str.charCodeAt(1) is:104
str.charCodeAt(2) is:105
str.charCodeAt(3) is:115
str.charCodeAt(4) is:32
str.charCodeAt(5) is:105
contact ()
This method adds two or more strings and returns a new single string.
Syntax
Its syntax is as follows:
Argument Details
string2...stringN: These are the strings to be concatenated.
Return Value
Returns a single concatenated string.
Example
Try the following example.
<html>
<head>
<title>JavaScript String concat() Method</title>
</head>
<body>
<script type="text/javascript">
var str1 = new String( "This is string one" );
var str2 = new String( "This is string two" );
var str3 = str1.concat( str2 );
Output
indexOf ()
This method returns the index within the calling String object of the first
occurrence of the specified value, starting the search at fromIndex or -1 if the
value is not found.
Syntax
Use the following syntax to use the indexOf() method.
string.indexOf(searchValue[, fromIndex])
Javascript
Argument Details
• searchValue: A string representing the value to search for.
• fromIndex: The location within the calling string to start the search from.
It can be any integer between 0 and the length of the string. The default
value is 0.
Return Value
Returns the index of the found occurrence, otherwise -1 if not found.
Example
Try the following example.
<html>
<head>
<title>JavaScript String indexOf() Method</title>
</head>
<body>
<script type="text/javascript">
var str1 = new String( "This is string one" );
var index = str1.indexOf( "string" );
document.write("indexOf found String :" + index );
document.write("<br />");
</script>
</body>
</html>
Output
lastIndexOf ()
This method returns the index within the calling String object of the last
occurrence of the specified value, starting the search at fromIndex or -1 if the
value is not found.
Syntax
Its syntax is as follows:
string.lastIndexOf(searchValue[, fromIndex])
Argument Details
• searchValue : A string representing the value to search for.
• fromIndex : The location within the calling string to start the search from.
It can be any integer between 0 and the length of the string. The default
value is 0.
Return Value
Returns the index of the last found occurrence, otherwise -1 if not found.
Example
Try the following example.
<html>
<head>
<title>JavaScript String lastIndexOf() Method</title>
</head>
<body>
<script type="text/javascript">
var str1 = new String( "This is string one and again string" );
var index = str1.lastIndexOf( "string" );
document.write("lastIndexOf found String :" + index );
document.write("<br />");
</script>
Javascript
</body>
</html>
Output
localeCompare ()
This method returns a number indicating whether a reference string comes
before or after or is the same as the given string in sorted order.
Syntax
The syntax of localeCompare() method is:
string.localeCompare( param )
Argument Details
param : A string to be compared with string object.
Return Value
• 0 : If the string matches 100%.
• 1 : no match, and the parameter value comes before the string object's
value in the locale sort order
• -1 : no match, and the parameter value comes after the string object's
value in the local sort order
Example
Try the following example.
<html>
<head>
<title>JavaScript String localeCompare() Method</title>
</head>
<body>
<script type="text/javascript">
var str1 = new String( "This is beautiful string" );
Javascript
document.write("<br />" );
</script>
</body>
</html>
Output
match ()
This method is used to retrieve the matches when matching a string against a
regular expression.
Syntax
Use the following syntax to use the match() method.
string.match ( param )
Argument Details
param : A regular expression object.
Return Value
• If the regular expression does not include the g flag, it returns the same
result as regexp.exec(string).
• If the regular expression includes the g flag, the method returns an Array
containing all the matches.
Example
Try the following example.
Javascript
<html>
<head>
<title>JavaScript String match() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "For more information, see Chapter 3.4.5.1";
var re = /(chapter \d+(\.\d)*)/i;
var found = str.match( re );
document.write(found );
</script>
</body>
</html>
Output
replace ()
This method finds a match between a regular expression and a string, and
replaces the matched substring with a new substring.
The replacement string can include the following special replacement patterns:
Pattern Inserts
$$ Inserts a "$".
$' Inserts the portion of the string that follows the matched
Javascript
substring.
Syntax
The syntax to use the replace() method is as follows:
Argument Details
• regexp : A RegExp object. The match is replaced by the return value of
parameter #2.
Return Value
It simply returns a new changed string.
Example
Try the following example.
<html>
<head>
<title>JavaScript String replace() Method</title>
</head>
<body>
<script type="text/javascript">
var re = /apples/gi;
Javascript
document.write(newstr );
</script>
</body>
</html>
Output
Example
Try the following example; it shows how to switch words in a string.
<html>
<head>
<title>JavaScript String replace() Method</title>
</head>
<body>
<script type="text/javascript">
var re = /(\w+)\s(\w+)/;
var str = "zara ali";
var newstr = str.replace(re, "$2, $1");
document.write(newstr);
</script>
</body>
</html>
Output
ali, zara
Javascript
Search ()
This method executes the search for a match between a regular expression and
this String object.
Syntax
Its syntax is as follows:
string.search(regexp);
Argument Details
regexp : A regular expression object. If a non-RegExp object obj is passed, it is
implicitly converted to a RegExp by using new RegExp(obj).
Return Value
If successful, the search returns the index of the regular expression inside the
string. Otherwise, it returns -1.
Example
Try the following example.
<html>
<head>
<title>JavaScript String search() Method</title>
</head>
<body>
<script type="text/javascript">
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
if ( str.search(re) == -1 ){
document.write("Does not contain Apples" );
}else{
document.write("Contains Apples" );
}
</script>
Javascript
</body>
</html>
Output
Contains Apples
slice ()
This method extracts a section of a string and returns a new string.
Syntax
The syntax for slice() method is:
Argument Details
• beginSlice : The zero-based index at which to begin extraction.
Return Value
If successful, slice returns the index of the regular expression inside the string.
Otherwise, it returns -1.
Example
Try the following example.
<html>
<head>
<title>JavaScript String slice() Method</title>
</head>
<body>
<script type="text/javascript">
document.write( sliced );
</script>
</body>
</html>
Output
split ()
This method splits a String object into an array of strings by separating the
string into substrings.
Syntax
string.split([separator][, limit]);
Argument Details
• separator : Specifies the character to use for separating the string.
If separator is omitted, the array returned contains one element consisting of
the entire string.
Return Value
The split method returns the new array. Also, when the string is empty, split
returns an array containing one empty string, rather than an empty array.
Example
Try the following example.
<html>
<head>
Javascript
</script>
</body>
</html>
Output
Apples,are,round,
substr ()
This method returns the characters in a string beginning at the specified location
through the specified number of characters.
Syntax
The syntax to use substr() is as follows:
string.substr(start[, length]);
Argument Details
• start : Location at which to start extracting characters (an integer between 0
and one less than the length of the string).
Note: If start is negative, substr uses it as a character index from the end of the
string.
Return Value
The substr() method returns the new sub-string based on given parameters.
Example
Javascript
<html>
<head>
<title>JavaScript String substr() Method</title>
</head>
<body>
<script type="text/javascript">
</script>
</body>
</html>
Output
(1,2): pp
(-2,2): y.
(1): pples are round, and apples are juicy.
(-20, 2): nd
(20, 2): d
substring ()
This method returns a subset of a String object.
Syntax
The syntax to use substr() is as follows:
string.substring(indexA, [indexB])
Argument Details
Javascript
• indexA : An integer between 0 and one less than the length of the string.
Return Value
The substring method returns the new sub-string based on given parameters.
Example
Try the following example.
<html>
<head>
<title>JavaScript String substring() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and apples are juicy.";
document.write("(1,2): " + str.substring(1,2));
document.write("<br />(0,10): " + str.substring(0, 10));
document.write("<br />(5): " + str.substring(5));
</script>
</body>
</html>
Output
(1,2): p
(0,10): Apples are
(5): s are round, and apples are juicy.
toLocaleLowerCase()
This method is used to convert the characters within a string to lowercase while
respecting the current locale. For most languages, it returns the same output as
toLowerCase.
Syntax
Its syntax is as follows:
string.toLocaleLowerCase( )
Javascript
Return Value
Returns a string in lowercase with the current locale.
Example
Try the following example.
<html>
<head>
<title>JavaScript String toLocaleLowerCase() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toLocaleLowerCase( ));
</script>
</body>
</html>
Output
toLocaleUppereCase ()
This method is used to convert the characters within a string to uppercase while
respecting the current locale. For most languages, it returns the same output as
toUpperCase.
Syntax
Its syntax is as follows:
string.toLocaleUpperCase( )
Return Value
Returns a string in uppercase with the current locale.
Javascript
Example
Try the following example.
<html>
<head>
<title>JavaScript String toLocaleUpperCase() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toLocaleUpperCase( ));
</script>
</body>
</html>
Output
toLowerCase ()
This method returns the calling string value converted to lowercase.
Syntax
Its syntax is as follows:
string.toLowerCase( )
Return Value
Returns the calling string value converted to lowercase.
Example
Try the following example.
<html>
Javascript
<head>
<title>JavaScript String toLowerCase() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toLowerCase( ));
</script>
</body>
</html>
Output
toString ()
This method returns a string representing the specified object.
Syntax
Its syntax is as follows:
string.toString( )
Return Value
Example
Try the following example.
<html>
<head>
<title>JavaScript String toString() Method</title>
</head>
Javascript
<body>
<script type="text/javascript">
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toString( ));
</script>
</body>
</html>
Output
toUpperCase ()
This method returns the calling string value converted to uppercase.
Syntax
Its syntax is as follows:
string.toUpperCase( )
Return Value
Example
<html>
<head>
<title>JavaScript String toUpperCase() Method</title>
</head>
<body>
Javascript
<script type="text/javascript">
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toUpperCase( ));
</script>
</body>
</html>
Output
valueOf ()
This method returns the primitive value of a String object.
Syntax
string.valueOf( )
Return Value
Returns the primitive value of a String object.
Example
<html>
<head>
<title>JavaScript String valueOf() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String("Hello world");
document.write(str.valueOf( ));
</script>
</body>
</html>
Javascript
Output
Hello world
Method Description
In the following sections, we will have a few examples to demonstrate the usage
of string HTML wrappers.
anchor()
This method creates an HTML anchor that is used as a hypertext target.
Syntax
Its syntax is as follows:
string.anchor( anchorname )
Attribute details
anchorname: Defines a name for the anchor.
Return Value
Returns the string having the anchor tag.
Example
<html>
<head>
<title>JavaScript String anchor() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String("Hello world");
alert (str.anchor( "myanchor" ));
</script>
</body>
</html>
Javascript
Output
big()
This method causes a string to be displayed in a big font as if it were in a BIG
tag.
Syntax
The syntax to use big() is as follows:
string.big()
Return Value
Returns the string having <big> tag.
Example
<html>
<head>
<title>JavaScript String big() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String("Hello world");
alert(str.big());
</script>
</body>
</html>
Output
<big>Hello world</big>
Javascript
blink ()
This method causes a string to blink as if it were in a BLINK tag.
Syntax
The syntax for blink() method is as follows:
string.blink( )
Return Value
Returns the string having <blink> tag.
Example
<html>
<head>
<title>JavaScript String blink() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String("Hello world");
alert(str.blink());
</script>
</body>
</html>
Output
<blink>Hello world</blink>
bold ()
This method causes a string to be displayed as bold as if it were in a <b> tag.
Syntax
The syntax for bold() method is as follows:
Javascript
string.bold( )
Return Value
Returns the string having <bold> tag.
Example
<html>
<head>
<title>JavaScript String bold() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String("Hello world");
alert(str.bold());
</script>
</body>
</html>
Output
<b>Hello world</b>
fixed ()
This method causes a string to be displayed in fixed-pitch font as if it were in a
<tt> tag.
Syntax
Its syntax is as follows:
string.fixed( )
Return Value
Returns the string having <tt> tag.
Example
Javascript
<html>
<head>
<title>JavaScript String fixed() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String("Hello world");
alert(str.fixed());
</script>
</body>
</html>
Output
<tt>Hello world</tt>
fontColor ()
This method causes a string to be displayed in the specified color as if it were in
a <font color="color"> tag.
Syntax
Its syntax is as follows:
string.fontColor( color)
Attribute Details
color: A string expressing the color as a hexadecimal RGB triplet or as a string
literal.
Return Value
Returns the string with <font color="color"> tag.
Example
<html>
Javascript
<head>
<title>JavaScript String fontcolor() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String("Hello world");
alert(str.fontcolor( "red" ));
</script>
</body>
</html>
Output
fontsize ()
This method causes a string to be displayed in the specified size as if it were in a
<font size="size"> tag.
Syntax
Its syntax is as follows:
string.fontsize( size )
Attribute Details
size: An integer between 1 and 7, a string representing a signed integer
between 1 and 7.
Return Value
Returns the string with <font size="size"> tag.
Example
<html>
<head>
<title>JavaScript String fontsize() Method</title>
</head>
<body>
<script type="text/javascript">
alert(str.fontsize( 3 ));
</script>
</body>
</html>
Output
italics ()
This method causes a string to be italic, as if it were in an <i> tag.
Syntax
Its syntax is as follows:
string.italics ( )
Return Value
Returns the string with <i> tag.
Example
<html>
<head>
<title>JavaScript String italics() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String("Hello world");
alert(str.italics( ));
</script>
</body>
</html>
Output
<i>Hello world</i>
link ()
This method creates an HTML hypertext link that requests another URL.
Syntax
The syntax for link() method is as follows:
string.link ( hrefname )
Attribute Details
hrefname: Any string that specifies the HREF of the A tag; it should be a valid
URL.
Return Value
Returns the string with <a> tag.
Example
<html>
<head>
<title>JavaScript String link() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String("Hello world");
var URL = "http://www.tutorialspoint.com";
Output
small ()
This method causes a string to be displayed in a small font, as if it were in a
<small> tag.
Syntax
Its syntax is as follows:
string.small ( )
Return Value
Returns the string with <small> tag.
Example
<head>
<title>JavaScript String small() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String("Hello world");
alert(str.small());
</script>
</body>
</html>
Output
<small>Hello world</small>
strike ()
This method causes a string to be displayed as struck-out text, as if it were in a
<strike> tag.
Syntax
Its syntax is as follows:
string.strike ( )
Return Value
Returns the string with <strike> tag.
Example
<head>
<title>JavaScript String strike() Method</title>
</head>
<body>
<script type="text/javascript">
</script>
</body>
</html>
Output
<strike>Hello world</strike>
sub()
This method causes a string to be displayed as a subscript, as if it were in a
<sub> tag.
Syntax
Its syntax is as follows:
string.sub ( )
Return Value
Returns the string with <sub> tag.
Example
<html>
<head>
<title>JavaScript String sub() Method</title>
</head>
<body>
<script type="text/javascript">
</script>
</body>
</html>
Output
<sub>Hello world</sub>
sup ()
This method causes a string to be displayed as a superscript, as if it were in a
<sup> tag.
Syntax
Its syntax is as follows:
string.sup()
Return Value
Returns the string with <sup> tag.
Example
<html>
<head>
<title>JavaScript String sup() Method</title>
</head>
<body>
<script type="text/javascript">
</script>
</body>
</html>
Output
<sup>Hello world</sup>
Javascript
24. ARRAYS
The Array object lets you store multiple values in a single variable. It stores a
fixed-size sequential collection of elements of the same type. An array is used to
store a collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.
Syntax
Use the following syntax to create an Array Object.
The Array parameter is a list of strings or integers. When you specify a single
numeric parameter with the Array constructor, you specify the initial length of the
array. The maximum length allowed for an array is 4,294,967,295.
You will use ordinal numbers to access and to set values inside an array as
follows.
Array Properties
Here is a list of the properties of the Array object along with their description.
Property Description
In the following sections, we will have a few examples to illustrate the usage of
Array properties.
constructor
Javascript array constructor property returns a reference to the array function
that created the instance's prototype.
Syntax
Its syntax is as follows:
array.constructor
Return Value
Returns the function that created this object's instance.
Example
Try the following example.
<html>
<head>
<title>JavaScript Array constructor Property</title>
</head>
<body>
<script type="text/javascript">
var arr = new Array( 10, 20, 30 );
document.write("arr.constructor is:" + arr.constructor);
</script>
</body>
</html>
Javascript
Output
length
Javascript array length property returns an unsigned, 32-bit integer that
specifies the number of elements in an array.
Syntax
Its syntax is as follows:
array.length
Return Value
Returns the length of an array.
Example
Try the following example.
<html>
<head>
<title>JavaScript Array length Property</title>
</head>
<body>
<script type="text/javascript">
var arr = new Array( 10, 20, 30 );
document.write("arr.length is:" + arr.length);
</script>
</body>
</html>
Output
arr.length is:3
Javascript
Prototype
The prototype property allows you to add properties and methods to any object
(Number, Boolean, String, Date, etc.).
Note: Prototype is a global property which is available with almost all the
objects.
Syntax
Its syntax is as follows:
object.prototype.name = value
Example
Try the following example.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
</body>
</html>
Output
Array Methods
Here is a list of the methods of the Array object along with their description.
Method Description
In the following sections, we will have a few examples to demonstrate the usage
of Array methods.
Javascript
concat ()
Javascript array concat() method returns a new array comprised of this array
joined with two or more arrays.
Syntax
The syntax of concat() method is as follows:
Parameter Details
valueN : Arrays and/or values to concatenate to the resulting array.
Return Value
Returns the length of the array.
Example
Try the following example.
<html>
<head>
<title>JavaScript Array concat Method</title>
</head>
<body>
<script type="text/javascript">
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
Output
alphaNumeric : a,b,c,1,2,3
Javascript
every ()
Javascript array every method tests whether all the elements in an array passes
the test implemented by the provided function.
Syntax
Its syntax is as follows:
array.every(callback[, thisObject]);
Parameter Details
• callback : Function to test for each element.
Return Value
Returns true if every element in this array satisfies the provided testing function.
Compatibility
This method is a JavaScript extension to the ECMA-262 standard; as such it may
not be present in other implementations of the standard. To make it work, you
need to add the following code at the top of your script.
if (!Array.prototype.every)
{
Array.prototype.every = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
return true;
};
}
Example
Try the following example.
<html>
<head>
<title>JavaScript Array every Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.every)
{
Array.prototype.every = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
return true;
};
}
function isBigEnough(element, index, array) {
return (element >= 10);
Javascript
Output
filter ()
Javascript array filter() method creates a new array with all elements that pass
the test implemented by the provided function.
Syntax
Its syntax is as follows:
Parameter Details
• callback : Function to test for each element of an array.
Return Value
Returns created array.
Compatibility
This method is a JavaScript extension to the ECMA-262 standard; as such it may
not be present in other implementations of the standard. To make it work, you
need to add the following code at the top of your script.
if (!Array.prototype.filter)
Javascript
{
Array.prototype.filter = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
return res;
};
}
Example
Try the following example.
<html>
<head>
<title>JavaScript Array filter Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.filter)
{
Javascript
return res;
};
}
</script>
</body>
</html>
Output
Javascript
forEach ()
Javascript array forEach() method calls a function for each element in the
array.
Syntax
Its syntax is as follows:
array.forEach(callback[, thisObject]);
Parameter Details
• callback : Function to test for each element of an array.
Return Value
Returns the created array.
Compatibility
This method is a JavaScript extension to the ECMA-262 standard; as such it may
not be present in other implementations of the standard. To make it work, you
need to add following code at the top of your script.
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
};
}
Example
Try the following example.
<html>
<head>
<title>JavaScript Array forEach Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
</script>
</body>
</html>
Output
[0] is 12
[1] is 5
[2] is 8
[3] is 130
[4] is 44
indexOf ()
Javascript array indexOf() method returns the first index at which a given
element can be found in the array, or -1 if it is not present.
Syntax
Its syntax is as follows:
array.indexOf(searchElement[, fromIndex]);
Parameter Details
• searchElement : Element to locate in the array.
• fromIndex : The index at which to begin the search. Defaults to 0, i.e. the
whole array will be searched. If the index is greater than or equal to the
length of the array, -1 is returned.
Return Value
Returns the index of the found element.
Compatibility
This method is a JavaScript extension to the ECMA-262 standard; as such it may
not be present in other implementations of the standard. To make it work, you
need to add the following code at the top of your script.
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
Javascript
Example
Try the following example.
<html>
<head>
<title>JavaScript Array indexOf Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length;
Javascript
Output
index is : 2
index is : -1
Javascript
join ()
Javascript array join() method joins all the elements of an array into a string.
Syntax
Its syntax is as follows:
array.join(separator);
Parameter Details
separator : Specifies a string to separate each element of the array. If omitted,
the array elements are separated with a comma.
Return Value
Returns a string after joining all the array elements.
Example
Try the following example.
<html>
<head>
<title>JavaScript Array join Method</title>
</head>
<body>
<script type="text/javascript">
</html>
Output
str : First,Second,Third
str : First, Second, Third
str : First + Second + Third
lastIndexOf ()
Javascript array lastIndexOf() method returns the last index at which a given
element can be found in the array, or -1 if it is not present. The array is searched
backwards, starting at fromIndex.
Syntax
Its syntax is as follows:
array.join(separator);
Parameter Details
• searchElement : Element to locate in the array.
Return Value
Returns the index of the found element from the last.
Compatibility
if (!Array.prototype.lastIndexOf)
{
Array.prototype.lastIndexOf = function(elt /*, from*/)
{
var len = this.length;
Javascript
Example
Try the following example.
<html>
<head>
<title>JavaScript Array lastIndexOf Method</title>
Javascript
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.lastIndexOf)
{
Array.prototype.lastIndexOf = function(elt /*, from*/)
{
var len = this.length;
Output
index is : 2
index is : 5
map ()
Javascript array map() method creates a new array with the results of calling a
provided function on every element in this array.
Syntax
Its syntax is as follows:
array.map(callback[, thisObject]);
Parameter Details
• callback : Function that produces an element of the new Array from an
element of the current one.
Return Value
Returns the created array.
Compatibility
Javascript
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
return res;
};
}
Example
Try the following example.
<html>
<head>
<title>JavaScript Array map Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.map)
{
Javascript
return res;
};
}
</script>
</body>
</html>
Output
roots is : 1,2,3
pop ()
Javascript array pop() method removes the last element from an array and
returns that element.
Javascript
Syntax
Its syntax is as follows:
Array.pop();
Return Value
Returns the removed element from the array.
Example
Try the following example.
<html>
<head>
<title>JavaScript Array pop Method</title>
</head>
<body>
<script type="text/javascript">
var numbers = [1, 4, 9];
Output
element is : 9
element is : 4
push ()
Javascript array push() method appends the given element(s) in the last of the
array and returns the length of the new array.
Syntax
Javascript
Array.push();
Parameter Details
element1, ..., elementN: The elements to add to the end of the array.
Return Value
Returns the length of the new array.
Example
Try the following example.
<html>
<head>
<title>JavaScript Array push Method</title>
</head>
<body>
<script type="text/javascript">
var numbers = new Array(1, 4, 9);
length = numbers.push(20);
document.write("<br />new numbers is : " + numbers );
</script>
</body>
</html>
Output
reduce ()
Javascript array reduce() method applies a function simultaneously against two
values of the array (from left-to-right) as to reduce it to a single value.
Syntax
Its syntax is as follows:
array.reduce(callback[, initialValue]);
Parameter Details
• callback : Function to execute on each value in the array.
• initialValue : Object to use as the first argument to the first call of the
callback.
Return Value
Returns the reduced single value of the array.
Compatibility
if (!Array.prototype.reduce)
{
Array.prototype.reduce = function(fun /*, initial*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var i = 0;
if (arguments.length >= 2)
{
Javascript
var rv = arguments[1];
}
else
{
do
{
if (i in this)
{
rv = this[i++];
break;
}
return rv;
};
}
Example
Try the following example.
<html>
<head>
Javascript
var i = 0;
if (arguments.length >= 2)
{
var rv = arguments[1];
}
else
{
do
{
if (i in this)
{
rv = this[i++];
break;
}
return rv;
};
}
Output
total is : 6
reduceRight ()
Javascript array reduceRight() method applies a function simultaneously against
two values of the array (from right-to-left) as to reduce it to a single value.
Syntax
Its syntax is as follows:
array.reduceRight(callback[, initialValue]);
Parameter Details
Javascript
• initialValue : Object to use as the first argument to the first call of the
callback.
Return Value
Returns the reduced right single value of the array.
Compatibility
if (!Array.prototype.reduceRight)
{
Array.prototype.reduceRight = function(fun /*, initial*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var i = len - 1;
if (arguments.length >= 2)
{
var rv = arguments[1];
}
else
{
do
{
if (i in this)
{
Javascript
rv = this[i--];
break;
}
return rv;
};
}
Example
Try the following example.
<html>
<head>
<title>JavaScript Array reduceRight Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.reduceRight)
{
Array.prototype.reduceRight = function(fun /*, initial*/)
{
Javascript
var i = len - 1;
if (arguments.length >= 2)
{
var rv = arguments[1];
}
else
{
do
{
if (i in this)
{
rv = this[i--];
break;
}
return rv;
};
}
Output
total is : 6
reverse ()
Javascript array reverse() method reverses the element of an array. The first
array element becomes the last and the last becomes the first.
Syntax
Its syntax is as follows:
array.reverse();
Return Value
Returns the reversed single value of the array.
Example
Try the following example.
<html>
<head>
<title>JavaScript Array reverse Method</title>
</head>
Javascript
<body>
<script type="text/javascript">
var arr = [0, 1, 2, 3].reverse();
document.write("Reversed array is : " + arr );
</script>
</body>
</html>
Output
shift ()
Javascript array shift() method removes the first element from an array and
returns that element.
Syntax
Its syntax is as follows:
array.shift();
Return Value
Returns the removed single value of the array.
Example
Try the following example.
<html>
<head>
<title>JavaScript Array shift Method</title>
</head>
<body>
<script type="text/javascript">
var element = [105, 1, 2, 3].shift();
document.write("Removed element is : " + element );
</script>
</body>
Javascript
</html>
Output
slice ()
Javascript array slice() method extracts a section of an array and returns a new
array.
Syntax
Its syntax is as follows:
Parameter Details
• begin : Zero-based index at which to begin extraction. As a negative
index, start indicates an offset from the end of the sequence.
Return Value
Returns the extracted array based on the passed parameters.
Example
Try the following example.
<html>
<head>
<title>JavaScript Array slice Method</title>
</head>
<body>
<script type="text/javascript">
var arr = ["orange", "mango", "banana", "sugar", "tea"];
document.write("arr.slice( 1, 2) : " + arr.slice( 1, 2) );
document.write("<br />arr.slice( 1, 2) : " + arr.slice( 1, 3) );
</script>
</body>
Javascript
</html>
Output
arr.slice( 1, 2) : mango
arr.slice( 1, 2) : mango,banana
some ()
Javascript array some() method tests whether some element in the array
passes the test implemented by the provided function.
Syntax
Its syntax is as follows:
array.some(callback[, thisObject]);
Parameter Details
• callback : Function to test for each element.
Return Value
If some element pass the test, then it returns true, otherwise false.
Compatibility
if (!Array.prototype.some)
{
Array.prototype.some = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
{
if (i in this &&
fun.call(thisp, this[i], i, this))
return true;
}
return false;
};
}
Example
Try the following example.
<html>
<head>
<title>JavaScript Array some Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.some)
{
Array.prototype.some = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
return false;
};
}
Output
sort ()
Javascript array sort() method sorts the elements of an array.
Syntax
Its syntax is as follows:
array.sort( compareFunction );
Parameter Details
compareFunction: Specifies a function that defines the sort order. If omitted,
the array is sorted lexicographically.
Javascript
Return Value
Returns a sorted array.
Example
Try the following example.
<html>
<head>
<title>JavaScript Array sort Method</title>
</head>
<body>
<script type="text/javascript">
var arr = new Array("orange", "mango", "banana", "sugar");
</script>
</body>
</html>
Output
splice ()
Javascript array splice() method changes the content of an array, adding new
elements while removing old elements.
Syntax
Its syntax is as follows:
Parameter Details
• index: Index at which to start changing the array.
Javascript
• element1, ..., elementN: The elements to add to the array. If you don't
specify any elements, splice simply removes the elements from the array.
Return Value
Returns the extracted array based on the passed parameters.
Example
Try the following example.
<html>
<head>
<title>JavaScript Array splice Method</title>
</head>
<body>
<script type="text/javascript">
var arr = ["orange", "mango", "banana", "sugar", "tea"];
</script>
</body>
</html>
Output
toString ()
Javascript array toString() method returns a string representing the source
code of the specified array and its elements.
Syntax
Its syntax is as follows:
array.toString( );
Return Value
Returns a string representing the array.
Example
Try the following example.
<html>
<head>
<title>JavaScript Array toString Method</title>
</head>
<body>
<script type="text/javascript">
var arr = new Array("orange", "mango", "banana", "sugar");
</script>
</body>
</html>
Output
unshift ()
Javascript array unshift() method adds one or more elements to the beginning
of an array and returns the new length of the array.
Javascript
Syntax
Its syntax is as follows:
Parameter Details
element1, ..., elementN : The elements to add to the front of the array.
Return Value
Returns the length of the new array. It returns undefined in IE browser.
Example
Try the following example.
<html>
<head>
<title>JavaScript Array unshift Method</title>
</head>
<body>
<script type="text/javascript">
var arr = new Array("orange", "mango", "banana", "sugar");
</script>
</body>
</html>
Output
The Date object is a datatype built into the JavaScript language. Date objects
are created with the new Date() as shown below.
Once a Date object is created, a number of methods allow you to operate on it.
Most methods simply allow you to get and set the year, month, day, hour, minute,
second, and millisecond fields of the object, using either local time or UTC
(universal, or GMT) time.
The ECMAScript standard requires the Date object to be able to represent any
date and time, to millisecond precision, within 100 million days before or after
1/1/1970. This is a range of plus or minus 273,785 years, so JavaScript can
represent date and time till the year 275755.
Syntax
You can use any of the following syntaxes to create a Date object using Date()
constructor.
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
• 7 agruments: To use the last form of the constructor shown above. Here
is a description of each argument:
Javascript
o year: Integer value representing the year. For compatibility (in order
to avoid the Y2K problem), you should always specify the year in full;
use 1998, rather than 98.
Date Properties
Here is a list of the properties of the Date object along with their description.
Property Description
In the following sections, we will have a few examples to demonstrate the usage
of different Date properties.
constructor
Javascript date constructor property returns a reference to the array function
that created the instance's prototype.
Syntax
Its syntax is as follows:
date.constructor
Javascript
Return Value
Returns the function that created this object's instance.
Example
Try the following example.
<html>
<head>
<title>JavaScript Date constructor Property</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date();
document.write("dt.constructor is : " + dt.constructor);
</script>
</body>
</html>
Output
Prototype
The prototype property allows you to add properties and methods to any object
(Number, Boolean, String, Date, etc.).
Note: Prototype is a global property which is available with almost all the
objects.
Syntax
Its syntax is as follows:
object.prototype.name = value
Javascript
Example
Try the following example.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
Output
Date Methods
Here is a list of the methods used with Date and their description.
Method Description
getDate() Returns the day of the month for the specified date
according to local time.
getDay() Returns the day of the week for the specified date
according to local time.
universal time.
In the following sections, we will have a few examples to demonstrate the usage
of Date methods.
Javascript
Date()
Javascript Date() method returns today's date and time and does not need any
object to be called.
Syntax
Its syntax is as follows:
Date()
Return Value
Returns today's date and time.
Example
Try the following example.
<html>
<head>
<title>JavaScript Date Method</title>
</head>
<body>
<script type="text/javascript">
var dt = Date();
document.write("Date and Time : " + dt );
</script>
</body>
</html>
Output
Date and Time : Wed Mar 25 2015 15:00:57 GMT+0530 (India Standard Time)
getDate()
Javascript date getDate() method returns the day of the month for the specified
date according to local time. The value returned by getDate is an integer between
1 and 31.
Javascript
Syntax
Its syntax is as follows:
Date.getDate()
Return Value
Returns today's date and time.
Example
Try the following example.
<html>
<head>
<title>JavaScript getDate Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date("December 25, 1995 23:15:00");
document.write("getDate() : " + dt.getDate() );
</script>
</body>
</html>
Output
getDate() : 25
getDay()
Javascript date getDay() method returns the day of the week for the specified
date according to local time. The value returned by getDay is an integer
corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday,
and so on.
Syntax
Its syntax is as follows:
Date.getDay()
Javascript
Return Value
Returns the day of the week for the specified date according to local time.
Example
Try the following example.
<html>
<head>
<title>JavaScript getDay Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date("December 25, 1995 23:15:00");
document.write("getDay() : " + dt.getDay() );
</script>
</body>
</html>
Output
getDay() : 1
getFullYear()
Javascript date getFullYear() method returns the year of the specified date
according to local time. The value returned by getFullYear is an absolute number.
For dates between the years 1000 and 9999, getFullYear returns a four-digit
number, for example, 2008.
Syntax
Its syntax is as follows:
Date.getFullYear()
Return Value
Returns the year of the specified date according to local time.
Javascript
Example
Try the following example.
<html>
<head>
<title>JavaScript getFullYear Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date("December 25, 1995 23:15:00");
document.write("getFullYear() : " + dt.getFullYear() );
</script>
</body>
</html>
Output
getFullYear() : 1995
getHours()
Javascript Date getHours() method returns the hour in the specified date
according to local time. The value returned by getHours is an integer between 0
and 23.
Syntax
Its syntax is as follows:
Date.getHours()
Return Value
Returns the hour in the specified date according to local time.
Example
Javascript
<html>
<head>
<title>JavaScript getHours Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date("December 25, 1995 23:15:00");
document.write("getHours() : " + dt.getHours() );
</script>
</body>
</html>
Output
getHours() : 23
getMilliseconds()
Javascript date getMilliseconds() method returns the milliseconds in the
specified date according to local time. The value returned by getMilliseconds is
a number between 0 and 999.
Syntax
Date.getMilliseconds ()
Return Value
Returns the milliseconds in the specified date according to local time.
Example
Try the following example.
<html>
<head>
<title>JavaScript getMilliseconds Method</title>
</head>
Javascript
<body>
<script type="text/javascript">
var dt = new Date();
document.write("getMilliseconds() : " + dt.getMilliseconds() );
</script>
</body>
</html>
Output
getMilliseconds() : 641
getMinutes ()
Javascript date getMinutes() method returns the minutes in the specified date
according to local time. The value returned by getMinutes is an integer between
0 and 59.
Syntax
Its syntax is as follows:
Date.getMinutes ()
Return Value
Returns the minutes in the specified date according to local time.
Example
Try the following example.
<html>
<head>
<title>JavaScript getMinutes Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "December 25, 1995 23:15:00" );
document.write("getMinutes() : " + dt.getMinutes() );
</script>
Javascript
</body>
</html>
Output
getMinutes() : 15
getMonth ()
Javascript date getMonth() method returns the month in the specified date
according to local time. The value returned by getMonth is an integer between
0 and 11. 0 corresponds to January, 1 to February, and so on.
Syntax
Its syntax is as follows:
Date.getMonth ()
Return Value
Returns the Month in the specified date according to local time.
Example
Try the following example.
<html>
<head>
<title>JavaScript getMonth Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "December 25, 1995 23:15:00" );
document.write("getMonth() : " + dt.getMonth() );
</script>
</body>
</html>
Output
Javascript
getMonth() : 11
getSeconds ()
Javascript date getSeconds() method returns the seconds in the specified date
according to local time. The value returned by getSeconds is an integer between
0 and 59.
Syntax
Its syntax is as follows:
Date.getSeconds ()
Return Value
Returns the seconds in the specified date according to local time.
Example
Try the following example.
<html>
<head>
<title>JavaScript getSeconds Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "December 25, 1995 23:15:20" );
document.write("getSeconds() : " + dt.getSeconds() );
</script>
</body>
</html>
Output
getSeconds () : 20
getTime ()
Javascript date getTime() method returns the numeric value corresponding to
the time for the specified date according to universal time. The value returned
Javascript
You can use this method to help assign a date and time to another Date object.
Syntax
Its syntax is as follows:
Date.getTime ()
Return Value
Returns the numeric value corresponding to the time for the specified date
according to universal time.
Example
Try the following example.
<html>
<head>
<title>JavaScript getTime Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "December 25, 1995 23:15:20" );
document.write("getTime() : " + dt.getTime() );
</script>
</body>
</html>
Output
getTime() : 819913520000
getTimezoneOffset ()
Javascript date getTimezoneOffset() method returns the time-zone offset in
minutes for the current locale. The time-zone offset is the minutes in difference,
the Greenwich Mean Time (GMT) is relative to your local time.
For example, if your time zone is GMT+10, -600 will be returned. Daylight savings
time prevents this value from being a constant.
Javascript
Syntax
Its syntax is as follows:
Date.getTimezoneOffset ()
Return Value
Returns the time-zone offset in minutes for the current locale.
Example
Try the following example.
<html>
<head>
<title>JavaScript getTimezoneOffset Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date();
var tz = dt.getTimezoneOffset();
document.write("getTimezoneOffset() : " + tz );
</script>
</body>
</html>
Output
getTimezoneOffset() : -330
getUTCDate ()
Javascript date getUTCDate() method returns the day of the month in the specified
date according to universal time. The value returned by getUTCDate isan integer
between 1 and 31.
Syntax
Its syntax is as follows:
Date.getUTCDate ()
Javascript
Return Value
Returns the day of the month in the specified date according to universal time.
Example
Try the following example.
<html>
<head>
<title>JavaScript getUTCDate Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "December 25, 1995 23:15:20" );
document.write("getUTCDate() : " + dt.getUTCDate() );
</script>
</body>
</html>
Output
getUTCDate() : 25
getUTCDay ()
Javascript date getUTCDay() method returns the day of the week in the specified
date according to universal time. The value returned by getUTCDay is an integer
corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday,
and so on.
Syntax
Its syntax is as follows:
Date.getUTCDay ()
Return Value
Returns the day of the week in the specified date according to universal time.
Example
Javascript
<html>
<head>
<title>JavaScript getUTCDay Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "December 25, 1995 23:15:20" );
document.write("getUTCDay() : " + dt.getUTCDay() );
</script>
</body>
</html>
Output
getUTCDay() : 1
getUTCFullYear ()
Javascript date getUTCFullYear() method returns the year in the specified date
according to universal time. The value returned by getUTCFullYear is an absolute
number that is compliant with year-2000, for example, 2008.
Syntax
Its syntax is as follows:
Date.getUTCFullYear ()
Return Value
Returns the year in the specified date according to universal time.
Example
Try the following example.
<html>
<head>
<title>JavaScript getUTCFullYear Method</title>
</head>
Javascript
<body>
<script type="text/javascript">
var dt = new Date( "December 25, 1995 23:15:20" );
document.write("getUTCFullYear() : " + dt.getUTCFullYear() );
</script>
</body>
</html>
Output
getUTCFullYear() : 1995
getUTCHours ()
Javascript date getUTCHours() method returns the hours in the specified date
according to universal time. The value returned by getUTCHours is an integer
between 0 and 23.
Syntax
Its syntax is as follows:
Date.getUTCHours ()
Return Value
Returns the hours in the specified date according to universal time.
Example
Try the following example.
<html>
<head>
<title>JavaScript getUTCHours Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date();
document.write("getUTCHours() : " + dt.getUTCHours() );
</script>
Javascript
</body>
</html>
Output
getUTCHours() : 11
getUTCMilliseconds ()
Javascript date getUTCMilliseconds() method returns the milliseconds in the
specified date according to universal time. The value returned by
getUTCMilliseconds is an integer between 0 and 999.
Syntax
Its syntax is as follows:
Date.getUTCMilliseconds ()
Return Value
Returns the milliseconds in the specified date according to universal time.
Example
Try the following example.
<html>
<head>
<title>JavaScript getUTCMilliseconds Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date();
document.write("getUTCMilliseconds() : " + dt.getUTCMilliseconds() );
</script>
</body>
</html>
Output
getUTCMilliseconds() : 206
Javascript
getUTCMinutes ()
Javascript date getUTCMinutes() method returns the minutes in the specified
date according to universal time. The value returned by getUTCMinutes is an
integer between 0 and 59.
Syntax
Its syntax is as follows:
Date.getUTCMinutes ()
Return Value
Returns the minutes in the specified date according to universal time.
Example
Try the following example.
<html>
<head>
<title>JavaScript getUTCMinutes Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date();
document.write("getUTCMinutes() : " + dt.getUTCMinutes() );
</script>
</body>
</html>
Output
getUTCMinutes() : 18
getUTCMonth ()
Javascript date getUTCMonth() method returns the month in the specified date
according to universal time. The value returned by getUTCMonth is an integer
between 0 and 11 corresponding to the month. 0 for January, 1 for February, 2
for March, and so on.
Javascript
Syntax
Its syntax is as follows:
Date.getUTCMonth ()
Return Value
Returns the month in the specified date according to universal time.
Example
Try the following example.
<html>
<head>
<title>JavaScript getUTCMonth Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date();
document.write("getUTCMonth() : " + dt.getUTCMonth() );
</script>
</body>
</html>
Output
getUTCMonth() : 2
getUTCSeconds ()
Javascript date getUTCSeconds() method returns the seconds in the specified
date according to universal time. The value returned by getUTCSeconds is an
integer between 0 and 59.
Syntax
Its syntax is as follows:
Date.getUTCSeconds ()
Return Value
Returns the month in the specified date according to universal time.
Javascript
Example
Try the following example.
<html>
<head>
<title>JavaScript getUTCSeconds Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date();
document.write("getUTCSeconds() : " + dt.getUTCSeconds() );
</script>
</body>
</html>
Output
getUTCSeconds() : 24
getYear ()
Javascript date getYear() method returns the year in the specified date according
to universal time. The getYear is no longer used and has been replaced by the
getFullYear method.
The value returned by getYear is the current year minus 1900. JavaScript 1.2
and earlier versions return either a 2-digit or 4-digit year. For example, if the year
is 2026, the value returned is 2026. So before testing this function, you need to
be sure of the javascript version you are using.
Syntax
Its syntax is as follows:
Date.getYear ()
Return Value
Returns the year in the specified date according to universal time.
Example
Try the following example.
Javascript
<html>
<head>
<title>JavaScript getYear Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date();
document.write("getYear() : " + dt.getYear() );
</script>
</body>
</html>
Output
getYear() : 115
setDate ()
Javascript date setDate() method sets the day of the month for a specified date
according to local time.
Syntax
Its syntax is as follows:
Date.setDate( dayValue )
Parameter Detail
dayValue : An integer from 1 to 31, representing the day of the month.
Example
Try the following example.
<html>
<head>
<title>JavaScript setDate Method</title>
</head>
<body>
<script type="text/javascript">
Javascript
Output
setFullYear ()
Javascript date setFullYear() method sets the full year for a specified date
according to local time.
Syntax
Its syntax is as follows:
Parameter Detail
• yearValue : An integer specifying the numeric value of the year, for
example, 2008.
If you do not specify the monthValue and dayValue parameters, the values
returned from the getMonth and getDate methods are used.
Example
Try the following example.
<html>
Javascript
<head>
<title>JavaScript setFullYear Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setFullYear( 2000 );
document.write( dt );
</script>
</body>
</html>
Output
setHours ()
Javascript date setHours() method sets the hours for a specified date according
to local time.
Syntax
Its syntax is as follows:
Parameter Detail
• hoursValue : An integer between 0 and 23, representing the hour.
Example
Try the following example.
<html>
<head>
<title>JavaScript setHours Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setHours( 02 );
document.write( dt );
</script>
</body>
</html>
Output
setMilliseconds ()
Javascript date setMilliseconds() method sets the milliseconds for a specified
date according to local time.
Syntax
Its syntax is as follows:
Date.setMilliseconds(millisecondsValue)
Parameter Detail
millisecondsValue : A number between 0 and 999, representing the
milliseconds.
Javascript
If you specify a number outside the expected range, the date information in the
Date object is updated accordingly. For example, if you specify 1010, thenumber
of seconds is incremented by 1, and 10 is used for the milliseconds.
Example
Try the following example.
<html>
<head>
<title>JavaScript setMilliseconds Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setMilliseconds( 1010 );
document.write( dt );
</script>
</body>
</html>
Output
setMinutes ()
Javascript date setMinutes() method sets the minutes for a specified date
according to local time.
Syntax
Its syntax is as follows:
Parameter Detail
• minutesValue : An integer between 0 and 59, representing the minutes.
Javascript
If you do not specify the secondsValue and msValue parameters, the values
returned from getSeconds and getMilliseconds methods are used.
<html>
<head>
<title>JavaScript setMinutes Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setMinutes( 45 );
document.write( dt );
</script>
</body>
</html>
Output
setMonth ()
Javascript date setMonth() method sets the month for a specified date
according to local time.
Syntax
The following syntax for setMonth () Method.
Date.setMonth(monthValue[, dayValue])
Parameter Detail
Javascript
If you do not specify the dayValue parameter, the value returned from the getDate
method is used. If a parameter you specify is outside of the expected range,
setMonth attempts to update the date information in the Date object accordingly.
For example, if you use 15 for monthValue, the year will beincremented by 1 (year
+ 1), and 3 will be used for month.
Example
Try the following example.
<html>
<head>
<title>JavaScript setMonth Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setMonth( 2 );
document.write( dt );
</script>
</body>
</html>
Output
setSeconds ()
Javascript date setSeconds() method sets the seconds for a specified date
according to local time.
Syntax
Javascript
Date.setSeconds(secondsValue[, msValue])
Parameter Detail
• secondsValue : An integer between 0 and 59.
If you do not specify the msValue parameter, the value returned from the
getMilliseconds method is used. If a parameter you specify is outside of the
expected range, setSeconds attempts to update the date information in the Date
object accordingly. For example, if you use 100 for secondsValue, the minutes
stored in the Date object will be incremented by 1, and 40 will be used for seconds.
Example
Try the following example.
<html>
<head>
<title>JavaScript setSeconds Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setSeconds( 80 );
document.write( dt );
</script>
</body>
</html>
Output
setTime ()
Javascript date setTime() method sets the Date object to the time represented
by a number of milliseconds since January 1, 1970, 00:00:00 UTC.
Syntax
Its syntax is as follows:
Date.setTime(timeValue)
Parameter Detail
Example
Try the following example.
<html>
<head>
<title>JavaScript setTime Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setTime( 5000000 );
document.write( dt );
</script>
</body>
</html>
Output
setUTCDate ()
Javascript date setUTCDate() method sets the day of the month for a specified
date according to universal time.
Javascript
Syntax
Its syntax is as follows:
Date.setUTCDate(dayValue)
Parameter Detail
dayValue : An integer from 1 to 31, representing the day of the month.
Example
Try the following example.
<html>
<head>
<title>JavaScript setUTCDate Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setUTCDate( 20 );
document.write( dt );
</script>
</body>
</html>
Output
setUTCFullYear ()
Javascript date setUTCFullYear() method sets the full year for a specified date
according to universal time.
Syntax
Its syntax is as follows:
Javascript
Parameter Detail
• yearValue : An integer specifying the numeric value of the year, for
example, 2008.
If you do not specify the monthValue and dayValue parameters, the values
returned from the getMonth and getDate methods are used. If a parameter you
specify is outside of the expected range, setUTCFullYear attempts to update the
other parameters and the date information in the Date object accordingly. For
example, if you specify 15 for monthValue, the year is incremented by 1 (year +
1), and 3 is used for the month.
Example
Try the following example.
<html>
<head>
<title>JavaScript setUTCFullYear Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setUTCFullYear( 2006 );
document.write( dt );
</script>
</body>
</html>
Output
setUTCHours ()
Javascript date setUTCHours() method sets the hour for a specified date
according to universal time.
Syntax
Its syntax is as follows:
Parameter Detail
• hoursValue : An integer between 0 and 23, representing the hour.
Example
Try the following example.
<html>
<head>
<title>JavaScript setUTCHours Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setUTCHours( 15 );
Javascript
document.write( dt );
</script>
</body>
</html>
Output
setUTCMilliseconds ()
Javascript date setUTCMilliseconds() method sets the milliseconds for a
specified date according to universal time.
Syntax
Its syntax is as follows:
Date.setUTCMilliseconds(millisecondsValue)
Parameter Detail
millisecondsValue : A number between 0 and 999, representing themilliseconds.
Example
Try the following example.
<html>
<head>
<title>JavaScript setUTCMilliseconds Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "Aug 28, 2008 23:30:00" );
dt.setUTCMilliseconds( 1100 );
Javascript
document.write( dt );
</script>
</body>
</html>
Output
setUTCMinutes ()
Javascript date setUTCMinutes() method sets the minutes for a specified date
according to universal time.
Syntax
Parameter Detail
• minutesValue : An integer between 0 and 59, representing the minutes.
If you do not specify the secondsValue and msValue parameters, the values
returned from getUTCSeconds and getUTCMilliseconds methods are used.
Example
Javascript
<html>
<head>
<title>JavaScript setUTCMinutes Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "Aug 28, 2008 13:30:00" );
dt.setUTCMinutes( 65 );
document.write( dt );
</script>
</body>
</html>
Output
setUTC Month ()
Javascript date setUTCMonth ( ) method sets the month for a specified date
according to universal time.
Syntax
The following syntax for setUTCMonth ( ) Method.
Date.setUTCMonth ( monthvalue )
Parameter Detail
monthValue : An integer between 0 and 11, representing the month.
Example
Try the following example.
Javascript
<html>
<head>
<title>JavaScript getUTCSeconds Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "Aug 28, 2008 13:30:00" );
dt.setUTCMonth( 2 );
document.write( dt );
</script>
</body>
</html>
Output
setUTCSeconds ()
Javascript date setUTCSeconds() method sets the seconds for a specified date
according to universal time.
Syntax
Its syntax is as follows:
Date.setUTCSeconds(secondsValue[, msValue])
Parameter Detail
• secondsValue : An integer between 0 and 59, representing the seconds.
If you do not specify the msValue parameter, the value returned from the
getUTCMilliseconds methods is used.
Example
Try the following example.
<html>
<head>
<title>JavaScript setUTCSeconds Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "Aug 28, 2008 13:30:00" );
dt.setUTCSeconds( 65 );
document.write( dt );
</script>
</body>
</html>
Output
setYear ()
Javascript date setYear() method sets the year for a specified date according to
universal time.
Syntax
Its syntax is as follows:
Date.setYear(yearValue)
Parameter Detail
yearValue: An integer value.
Example
Try the following example.
<html>
Javascript
<head>
<title>JavaScript setYear Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date( "Aug 28, 2008 13:30:00" );
dt.setYear( 2000 );
document.write( dt );
</script>
</body>
</html>
Output
toDateString ()
Javascript date toDateString() method returns the date portion of a Date
object in human readable form.
Syntax
Its syntax is as follows:
Date.toDateString()
Return Value
Returns the date portion of a Date object in human readable form.
Example
Try the following example.
<html>
<head>
<title>JavaScript toDateString Method</title>
</head>
<body>
<script type="text/javascript">
Javascript
Output
toGMTString ()
Javascript date toGMTString() method converts a date to a string, using
Internet GMT conventioins.
This method is no longer used and has been replaced by the toUTCString
method.
Syntax
Its syntax is as follows:
Date.toGMTString()
Return Value
Returns a date to a string, using Internet GMT conventioins.
Example
Try the following example.
<html>
<head>
<title>JavaScript toGMTString Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date(1993, 6, 28, 14, 39, 7);
document.write( "Formated Date : " + dt.toGMTString() );
</script>
</body>
Javascript
</html>
Output
toLocaleDateString ()
Javascript date toLocaleDateString() method converts a date to a string,
returning the "date" portion using the operating system's locale's conventions.
Syntax
Its syntax is as follows:
Date.toGMTString()
Return Value
Returns a date to a string, using Internet GMT conventioins.
Example
Try the following example.
<html>
<head>
<title>JavaScript toGMTString Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date(1993, 6, 28, 14, 39, 7);
document.write( "Formated Date : " + dt.toGMTString() );
</script>
</body>
</html>
Output
toLocaleDateString ()
Javascript date toLocaleDateString() method converts a date to a string,
returning the "date" portion using the operating system's locale's conventions.
Syntax
Its syntax is as follows:
Date.toLocaleString()
Return Value
Returns the "date" portion using the operating system's locale's conventions.
Example
Try the following example.
<html>
<head>
<title>JavaScript toLocaleDateString Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date(1993, 6, 28, 14, 39, 7);
document.write( "Formated Date : " + dt.toLocaleDateString() );
</script>
</body>
</html>
Output
toLocaleFormat ()
Javascript date toLocaleFormat() method converts a date to a string using the
specified formatting.
Note: This method may not compatible with all the browsers.
Javascript
Syntax
Its syntax is as follows:
Date.toLocaleFormat()
Parameter Details
formatString: A format string in the same format expected by the strftime()
function in C.
Return Value
Returns the formatted date.
Example
Try the following example.
<html>
<head>
<title>JavaScript toLocaleFormat Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date(1993, 6, 28, 14, 39, 7);
document.write( "Formated Date : " + dt.toLocaleFormat( "%A, %B %e, %Y" ));
</script>
</body>
</html>
Output
Formated Date : Wed Jul 28 1993 14:39:07 GMT+0530 (India Standard Time)
toLocaleString ()
Javascript date toLocaleString() method converts a date to a string, using the
operating system's local conventions.
Syntax
Its syntax is as follows:
Date.toLocaleString ()
Return Value
Returns the formatted date in a string fromat.
Example
Try the following example.
<html>
<head>
<title>JavaScript toLocaleString Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date(1993, 6, 28, 14, 39, 7);
document.write( "Formated Date : " + dt.toLocaleString() );
</script>
</body>
</html>
Output
toLocaleTimeSring ()
Javascript date toLocaleTimeString() method converts a date to a string,
returning the "date" portion using the current locale's conventions.
Syntax
Its syntax is as follows:
Javascript
Date.toLocaleTimeString ()
Return Value
Returns the formatted date in a string fromat.
Example
Try the following example.
<html>
<head>
<title>JavaScript toLocaleTimeString Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date(1993, 6, 28, 14, 39, 7);
document.write( "Formated Date : " + dt.toLocaleTimeString() );
</script>
</body>
</html>
Output
toSource ()
This method returns a string representing the source code of the object.
Note: This method may not be compatible with all the browsers.
Syntax
The following syntax for toSource () Method.
Date.toSource ()
Return Value
• For the built-in Date object, toSource returns a string (new
Date(...))indicating that the source code is not available
Javascript
Example
Try the following example.
<html>
<head>
<title>JavaScript toSource Method</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date(1993, 6, 28, 14, 39, 7);
document.write( "Formated Date : " + dt.toSource() );
</script>
</body>
</html>
Output
toString ()
This method returns a string representing the specified Date object.
Syntax
The following syntax for toString () Method.
Date.toString ()
Return Value
Returns a string representing the specified Date object.
Example
Try the following example.
<html>
Javascript
<head>
<title>JavaScript toString Method</title>
</head>
<body>
<script type="text/javascript">
var dateobject = new Date(1993, 6, 28, 14, 39, 7);
stringobj = dateobject.toString();
document.write( "String Object : " + stringobj );
</script>
</body>
</html>
Output
String Object : Wed Jul 28 1993 14:39:07 GMT+0530 (India Standard Time)
toTimeString ()
This method returns the time portion of a Date object in human readable form.
Syntax
Its syntax is as follows:
Date.toTimeString ()
Return Value
Returns the time portion of a Date object in human readable form.
Example
Try the following example.
<html>
<head>
<title>JavaScript toTimeString Method</title>
Javascript
</head>
<body>
<script type="text/javascript">
var dateobject = new Date(1993, 6, 28, 14, 39, 7);
document.write( dateobject.toTimeString() );
</script>
</body>
</html>
Output
toUTCString ()
This method converts a date to a string, using the universal time convention.
Syntax
Its syntax is as follows:
Date.toTimeString ()
Return Value
Returns converted date to a string, using the universal time convention.
Example
Try the following example.
<html>
<head>
<title>JavaScript toUTCString Method</title>
</head>
<body>
<script type="text/javascript">
var dateobject = new Date(1993, 6, 28, 14, 39, 7);
document.write( dateobject.toUTCString() );
</script>
</body>
Javascript
</html>
Output
valeOf ()
This method returns the primitive value of a Date object as a number data type,
the number of milliseconds since midnight 01 January, 1970 UTC.
Syntax
Its syntax is as follows:
Date.valueOf ()
Return Value
Returns the primitive value of a Date object.
Example
Try the following example.
<html>
<head>
<title>JavaScript valueOf Method</title>
</head>
<body>
<script type="text/javascript">
var dateobject = new Date(1993, 6, 28, 14, 39, 7);
document.write( dateobject.valueOf() );
</script>
</body>
</html>
Javascript
Output
743850547000
Method Description
Date.parse ( )
Javascript date parse() method takes a date string and returns the number of
milliseconds since midnight of January 1, 1970.
Syntax
Its syntax is as follows:
Date.parse(datestring)
Parameter Details
datestring: A string representing a date.
Return Value
Number of milliseconds since midnight of January 1, 1970.
Example
Javascript
<html>
<head>
<title>JavaScript parse Method</title>
</head>
<body>
<script type="text/javascript">
var msecs = Date.parse( "Aug 28, 2008 23:30:00" );
document.write( "Number of milliseconds from 1970: " + msecs );
</script>
</body>
</html>
Output
Date.UTC ( )
This method takes a date and returns the number of milliseconds since midnight
of January 1, 1970 according to universal time.
Syntax
Its syntax is as follows:
Date.year,month,day,[hours,[minutes,[seconds,[ms]]])
Parameter Details
• year : A four digit number representing the year.
Return Value
Number of milliseconds since midnight of January 1, 1970.
Example
Try the following example.
<html>
<head>
<title>JavaScript UTC Method</title>
</head>
<body>
<script type="text/javascript">
var msecs = Date.UTC(2008,9,6);
document.write( "Number of milliseconds from 1970: " + msecs );
</script>
</body>
</html>
Output
The math object provides you properties and methods for mathematical constants
and functions. Unlike other global objects, Math is not a constructor. All the
properties and methods of Math are static and can be called by using Math
as an object without creating it.
Thus, you refer to the constant pi as Math.PI and you call the sine function
as Math.sin(x), where x is the method's argument.
Syntax
The syntax to call the properties and methods of Math are as follows:
Math Properties
Here is a list of all the properties of Math and their description.
Property Description
275
Javascript
In the following sections, we will have a few examples to demonstrate the usage
of Math properties.
Math-E
This is an Euler's constant and the base of natural logarithms, approximately
2.718.
Syntax
Its syntax is as follows:
Math.E
Example
<html>
<head>
<title>JavaScript Math E Property</title>
</head>
<body>
<script type="text/javascript">
var property_value = Math.E
document.write("Property Value is :" + property_value);
</script>
</body>
</html>
Output
Math-LN2
It returns the natural logarithm of 2 which is approximately 0.693.
Syntax
Its syntax is as follows:
Math.LN2
Example
<html>
<head>
<title>JavaScript Math LN2 Property</title>
</head>
<body>
<script type="text/javascript">
var property_value = Math.LN2
document.write("Property Value is : " + property_value);
</script>
</body>
</html>
Output
Math-LN10
It returns the natural logarithm of 10 which is approximately 2.302.
Syntax
Its syntax is as follows:
Math.LN10
Javascript
Example
<html>
<head>
<title>JavaScript Math LN10 Property</title>
</head>
<body>
<script type="text/javascript">
var property_value = Math.LN10
document.write("Property Value is : " + property_value);
</script>
</body>
</html>
Output
Math-LOG2E
It returns the base 2 logarithm of E which is approximately 1.442.
Syntax
Its syntax is as follows:
Math.LOG2E
Example
<html>
<head>
<title>JavaScript Math LOG2E Property</title>
</head>
<body>
<script type="text/javascript">
Javascript
Output
Math-LOG10E
It returns the base 10 logarithm of E which is approximately 0.434.
Syntax
Its syntax is as follows:
Math.LOG10E
Example
<html>
<head>
<title>JavaScript Math LOG10E Property</title>
</head>
<body>
<script type="text/javascript">
var property_value = Math.LOG10E
document.write("Property Value is : " + property_value);
</script>
</body>
</html>
Output
Javascript
Math-PI
It returns the ratio of the circumference of a circle to its diameter which is
approximately 3.14159.
Syntax
Its syntax is as follows:
Math.PI
Example
<html>
<head>
<title>JavaScript Math PI Property</title>
</head>
<body>
<script type="text/javascript">
var property_value = Math.PI
document.write("Property Value is : " + property_value);
</script>
</body>
</html>
Output
Math-SQRT1_2
It returns the square root of 1/2; equivalently, 1 over the square root of 2 which
is approximately 0.707.
Javascript
Syntax
Its syntax is as follows:
Math.SQRT1_2
Example
<html>
<head>
<title>JavaScript Math SQRT1_2 Property</title>
</head>
<body>
<script type="text/javascript">
var property_value = Math.SQRT1_2
document.write("Property Value is : " + property_value);
</script>
</body>
</html>
Output
Math-SQRT2
It returns the square root of 2 which is approximately 1.414.
Syntax
Its syntax is as follows:
Math.SQRT2
Example
<html>
Javascript
<head>
<title>JavaScript Math SQRT2 Property</title>
</head>
<body>
<script type="text/javascript">
var property_value = Math.SQRT2
document.write("Property Value is : " + property_value);
</script>
</body>
</html>
Output
Math Methods
Here is a list of the methods associated with Math object and their description.
Method Description
number.
In the following sections, we will have a few examples to demonstrate the usage
of the methods associated with Math.
abs ()
This method returns the absolute value of a number.
Syntax
Its syntax is as follows:
Math.abs( x ) ;
Parameter Details
x: A number.
Return Value
Returns the absolute value of a number.
Example
Javascript
<html>
<head>
<title>JavaScript Math abs() Method</title>
</head>
<body>
<script type="text/javascript">
Output
acos ()
This method returns the arccosine in radians of a number. The acos method
returns a numeric value between 0 and pi radians for x between -1 and 1. If the
value of number is outside this range, it returns NaN.
Syntax
Javascript
Math.cos( x ) ;
Parameter Details
x: A number.
Return Value
Returns the arccosine in radians of a number.
Example
<html>
<head>
<title>JavaScript Math acos() Method</title>
</head>
<body>
<script type="text/javascript">
Output
Javascript
asin ( )
This method returns the arcsine in radians of a number. The asin method returns
a numeric value between -pi/2 and pi/2 radians for x between -1 and 1. If the
value of number is outside this range, it returns NaN.
Syntax
Its syntax is as follows:
Math.asin( x ) ;
Parameter Details
x: A number.
Return Value
Returns the arcsine in radians of a number.
Example
<html>
<head>
<title>JavaScript Math asin() Method</title>
</head>
<body>
<script type="text/javascript">
Output
atan ( )
This method returns the arctangent in radians of a number. The atan method
returns a numeric value between -pi/2 and pi/2 radians.
Syntax
Its syntax is as follows:
Math.atan( x ) ;
Parameter Details
x: A number.
Return Value
Returns the arctangent in radians of a number.
Example
<html>
<head>
Javascript
Output
atan2 ( )
This method returns the arctangent of the quotient of its arguments. The atan2
method returns a numeric value between -pi and pi representing the angle theta
of an (x, y) point.
Syntax
Its syntax is as follows:
Math.atan2 ( x, y ) ;
Javascript
Parameter Details
X and y: numbers.
Return Value
Returns the arctangent in radians of a number.
Example
<html>
<head>
<title>JavaScript Math atan2() Method</title>
</head>
<body>
<script type="text/javascript">
var value = Math.atan2(90,15);
document.write("First Test Value : " + value );
Output
ceil ( )
This method returns the smallest integer greater than or equal to a number.
Syntax
Its syntax is as follows:
Math.ceil ( x ) ;
Parameter Details
x: a number.
Return Value
Returns the smallest integer greater than or equal to a number.
Example
<html>
<head>
<title>JavaScript Math ceil() Method</title>
</head>
<body>
<script type="text/javascript">
Javascript
Output
cos ( )
This method returns the cosine of a number. The cos method returns a numeric
value between -1 and 1, which represents the cosine of the angle.
Syntax
Its syntax is as follows:
Math.cos ( x ) ;
Parameter Details
x: a number.
Return Value
Returns the cosine of a number.
Javascript
Example
<html>
<head>
<title>JavaScript Math cos() Method</title>
</head>
<body>
<script type="text/javascript">
Output
exp ( )
This method returns Ex, where x is the argument, and E is the Euler's constant,
the base of the natural logarithms.
Javascript
Syntax
Its syntax is as follows:
Math.exp ( x ) ;
Parameter Details
x: a number.
Return Value
Returns the exponential value of the variable x.
Example
<html>
<head>
<title>JavaScript Math exp() Method</title>
</head>
<body>
<script type="text/javascript">
Output
floor ( )
This method returns the largest integer less than or equal to a number.
Syntax
Its syntax is as follows:
Math.floor ( x ) ;
Parameter Details
x: a number.
Return Value
Returns the largest integer less than or equal to a number x.
Example
<html>
<head>
<title>JavaScript Math floor() Method</title>
</head>
<body>
<script type="text/javascript">
Output
log ( )
This method returns the natural logarithm (base E) of a number. If the value of
number is negative, the return value is always NaN.
Syntax
Its syntax is as follows:
Math.log ( x ) ;
Parameter Details
x: a number.
Return Value
Returns the natural logarithm (base E) of a number.
Example
<html>
<head>
<title>JavaScript Math log() Method</title>
</head>
<body>
Javascript
<script type="text/javascript">
Output
max ( )
This method returns the largest of zero or more numbers. If no arguments are
given, the results is –Infinity.
Syntax
Its syntax is as follows:
Parameter Details
value1, value2, ... valueN : Numbers.
Return Value
Javascript
Example
<html>
<head>
<title>JavaScript Math max() Method</title>
</head>
<body>
<script type="text/javascript">
Output
min ( )
This method returns the smallest of zero or more numbers. If no arguments are
given, the results is +Infinity.
Syntax
Its syntax is as follows:
Parameter Details
value1, value2, ... valueN : Numbers.
Return Value
Returns the smallest of zero or more numbers.
Example
<html>
<head>
<title>JavaScript Math min() Method</title>
</head>
<body>
<script type="text/javascript">
</script>
</body>
</html>
Output
pow ( )
This method returns the base to the exponent power, that is, baseexponent.
Syntax
Its syntax is as follows:
Math.pow(base, exponent );
Parameter Details
• base : The base number.
Return Value
Returns the base to the exponent power, that is, baseexponent.
Example
<html>
<head>
<title>JavaScript Math pow() Method</title>
</head>
<body>
<script type="text/javascript">
Javascript
Output
random ( )
This method returns a random number between 0 (inclusive) and 1 (exclusive).
Syntax
Its syntax is as follows:
Math.random ( );
Return Value
Returns a random number between 0 (inclusive) and 1 (exclusive).
Example
<html>
<head>
<title>JavaScript Math random() Method</title>
</head>
<body>
<script type="text/javascript">
Output
round ( )
This method returns the value of a number rounded to the nearest integer.
Syntax
Its syntax is as follows:
Math.round ( );
Javascript
Return Value
Returns the value of a number rounded to the nearest integer.
Example
<html>
<head>
<title>JavaScript Math round() Method</title>
</head>
<body>
<script type="text/javascript">
Output
sin ( )
This method returns the sine of a number. The sin method returns a numeric
value between -1 and 1, which represents the sine of the argument.
Syntax
Its syntax is as follows:
Math.sin ( x );
Parameter Details
x: A number.
Return Value
Returns the sine of a number.
Example
<html>
<head>
<title>JavaScript Math sin() Method</title>
</head>
<body>
<script type="text/javascript">
</script>
</body>
</html>
Output
sqrt ( )
This method returns the square root of a number. If the value of a number is
negative, sqrt returns NaN.
Syntax
Its syntax is as follows:
Math.sqrt ( x );
Parameter Details
x: A number.
Return Value
Returns the square root of a given number.
Example
<html>
<head>
<title>JavaScript Math sqrt() Method</title>
</head>
<body>
<script type="text/javascript">
Javascript
Output
tan ( )
This method returns the tangent of a number. The tan method returns a numeric
value that represents the tangent of the angle.
Syntax
Its syntax is as follows:
Math.tan ( x );
Parameter Details
x: A number representing an angle in radians.
Return Value
Returns the tangent of a number.
Javascript
Example
<html>
<head>
<title>JavaScript Math tan() Method</title>
</head>
<body>
<script type="text/javascript">
Output
toSource ( )
This method returns the string "Math". But this method does not work with IE.
Javascript
Syntax
Its syntax is as follows:
Math.toSource ( );
Return Value
Returns the string “Math”.
Example
<html>
<head>
<title>JavaScript Math toSource() Method</title>
</head>
<body>
<script type="text/javascript">
</script>
</body>
</html>
Output
Value : Math
Javascript
27. REGEXP
The JavaScript RegExp class represents regular expressions, and both String and
RegExp define methods that use regular expressions to perform powerful pattern-
matching and search-and-replace functions on text.
Syntax
A regular expression could be defined with the RegExp() constructor, as follows:
or simply
• attributes: An optional string containing any of the "g", "i", and "m"
attributes that specify global, case-insensitive, and multiline matches,
respectively.
Brackets
Brackets ([]) have a special meaning when used in the context of regular
expressions. They are used to find a range of characters.
Expression Description
The ranges shown above are general; you could also use the range [0-3] to match
any decimal digit ranging from 0 through 3, or the range [b-v] to match any
lowercase character ranging from b through v.
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.
Expression Description
309
Javascript
Examples
Following examples explain more about matching characters.
Expression Description
Literal Characters
Character Description
Alphanumeric Itself
\t Tab (\u0009)
\n Newline (\u000A)
310
Javascript
\cX The control character ^X; for example, \cJ is equivalent to the
newline character \n
Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash
that acts to give the combination a special meaning.
For instance, you can search for a large sum of money using the '\d'
metacharacter: /([\d]+)000/. Here \d will search for any string of numerical
character.
The following table lists a set of metacharacters which can be used in PERL Style
Regular Expressions.
Character Description
. a single character
\S non-whitespace character
\d a digit (0-9)
\D a non-digit
\W a non-word character
Modifiers
Several modifiers are available that can simplify the way you work with
regexps, like case sensitivity, searching in multiple lines, etc.
Modifier Description
311
Javascript
RegExp Properties
Here is a list of the properties associated with RegExp and their description.
Property Description
In the following sections, we will have a few examples to demonstrate the usage
of RegExp properties.
constructor
It returns a reference to the array function that created the instance's prototype.
Syntax
Its syntax is as follows:
RegExp.constructor
Return Value
Returns the function that created this object's instance.
312
Javascript
Example
<html>
<head>
<title>JavaScript RegExp constructor Property</title>
</head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
document.write("re.constructor is:" + re.constructor);
</script>
</body>
</html>
Output
global
global is a read-only boolean property of RegExp objects. It specifies whether a
particular regular expression performs global matching, i.e., whether it was
created with the "g" attribute.
Syntax
Its syntax is as follows:
RegExpObject.global
Return Value
Returns "TRUE" if the "g" modifier is set, "FALSE" otherwise.
Example
313
Javascript
<html>
<head>
<title>JavaScript RegExp global Property</title>
</head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
if ( re.global ){
document.write("Test1 - Global property is set");
}else{
document.write("Test1 - Global property is not set");
}
re = new RegExp( "string", "g" );
if ( re.global ){
document.write("<br />Test2 - Global property is set");
}else{
document.write("<br />Test2 - Global property is not set");
}
</script>
</body>
</html>
Output
ignoreCase
ignoreCase is a read-only boolean property of RegExp objects. It specifies
whether a particular regular expression performs case-insensitive matching, i.e.,
whether it was created with the "i" attribute.
314
Javascript
Syntax
Its syntax is as follows:
RegExpObject.ignoreCase
Return Value
Returns "TRUE" if the "i" modifier is set, "FALSE" otherwise.
Example
Try the following example program.
<html>
<head>
<title>JavaScript RegExp ignoreCase Property</title>
</head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
if ( re.ignoreCase ){
document.write("Test1 - ignoreCase property is set");
}else{
document.write("Test1 - ignoreCase property is not set");
}
re = new RegExp( "string", "i" );
if ( re.ignoreCase ){
document.write("<br />Test2 - ignoreCase property is set");
}else{
document.write("<br />Test2 - ignoreCase property is not set");
}
</script>
</body>
</html>
Output
315
Javascript
lastIndex
lastIndex is a read/write property of RegExp objects. For regular expressions
with the "g" attribute set, it contains an integer that specifies the character
position immediately following the last match found by the
RegExp.exec() and RegExp.test() methods. These methods use thisproperty
as the starting point for the next search they conduct.
This property allows you to call those methods repeatedly, to loop through all
matches in a string and works only if the "g" modifier is set.
This property is read/write, so you can set it at any time to specify where in the
target string, the next search should begin. exec() and test() automatically reset
the lastIndex to 0 when they fail to find a match (or another match).
Syntax
Its syntax is as follows:
RegExpObject.lastIndex
Return Value
Returns an integer that specifies the character position immediately following
the last match.
Example
<html>
<head>
<title>JavaScript RegExp lastIndex Property</title>
</head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
re.test(str);
316
Javascript
re.test(str);
document.write("<br />Test 2 - Current Index: " + re.lastIndex);
</script>
</body>
</html>
Output
multiline
multiline is a read-only boolean property of RegExp objects. It specifies whether
a particular regular expression performs multiline matching, i.e., whether it was
created with the "m" attribute.
Syntax
Its syntax is as follows:
RegExpObject.multiline
Return Value
Returns "TRUE" if the "m" modifier is set, "FALSE" otherwise.
Example
<html>
<head>
<title>JavaScript RegExp multiline Property</title>
</head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
317
Javascript
if ( re.multiline ){
document.write("Test1-multiline property is set");
}else{
document.write("Test1-multiline property is not set");
}
re = new RegExp( "string", "m" );
if ( re.multiline ){
document.write("<br/>Test2-multiline property is set");
}else{
document.write("<br/>Test2-multiline property is not set");
}
</script>
</body>
</html>
Output
source
source is a read-only string property of RegExp objects. It contains the text of
the RegExp pattern. This text does not include the delimiting slashes used in
regular-expression literals, and it does not include the "g", "i", and "m" attributes.
Syntax
Its syntax is as follows:
RegExpObject.source
Return Value
Returns the text used for pattern matching.
Example
318
Javascript
<html>
<head>
<title>JavaScript RegExp source Property</title>
</head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
re.test(str);
document.write("The regular expression is : " + re.source);
</script>
</body>
</html>
Output
RegExp Methods
Here is a list of the methods associated with RegExp along with their description.
Method Description
In the following sections, we will have a few examples to demonstrate the usage
of RegExp methods.
319
Javascript
exec ( )
The exec method searches string for text that matches regexp. If it finds a
match, it returns an array of results; otherwise, it returns null.
Syntax
Its syntax is as follows:
RegExpObject.exec( string );
Parameter Details
string: The string to be searched.
Return Value
Returns the matched text if a match is found, and null if not.
Example
<html>
<head>
<title>JavaScript RegExp exec Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
320
Javascript
Output
test ( )
The test method searches string for text that matches regexp. If it finds a
match, it returns true; otherwise, it returns false.
Syntax
Its syntax is as follows:
RegExpObject.test( string );
Parameter Details
string: The string to be searched.
Return Value
Returns the matched text if a match is found, and null if not.
Example
<html>
<head>
<title>JavaScript RegExp test Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
321
Javascript
Output
toSource ( )
The toSource method string represents the source code of the object. This
method does not work with all the browsers.
Syntax
Its syntax is as follows:
RegExpObject.toSource ( string );
Return Value
Returns the string representing the source code of the object.
Example
<html>
<head>
<title>JavaScript RegExp toSource Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
322
Javascript
Output
toString ( )
The toString method returns a string representation of a regular expression in
the form of a regular-expression literal.
Syntax
Its syntax is as follows:
RegExpObject.toString ( );
Return Value
Returns the string representing of a regular expression.
Example
<html>
<head>
<title>JavaScript RegExp toString Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
Output
324
Javascript
325