293
Java Script Tutorial by Mohammad Abdollahi http://www.abdollahi.us 1

Java Script Tutorial

  • Upload
    zanthe

  • View
    18

  • Download
    1

Embed Size (px)

DESCRIPTION

Java Script Tutorial. by Mohammad Abdollahi http://www.abdollahi.us. Subjects. JS Basic JS Objects JS Advanced. JS Basic. JS Introduction JS How To JS Where To JS Statements JS Comments JS Variables - PowerPoint PPT Presentation

Citation preview

Page 1: Java Script Tutorial

1

Java Script Tutorial

by Mohammad Abdollahihttp://www.abdollahi.us

Page 2: Java Script Tutorial

SubjectsJS BasicJS ObjectsJS Advanced

Page 3: Java Script Tutorial

JS Basic

JS IntroductionJS How ToJS Where ToJS StatementsJS CommentsJS VariablesJS Data TypesJS OperatorsJS ComparisonsJS If...ElseJS SwitchJS Popup BoxesJS Functions

JS For LoopJS While LoopJS Break LoopsJS For...InJS EventsJS Try...CatchJS ThrowJS Special TextJS Guidelines

Page 4: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

4 /294

JS Introduction

• JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari.

• What You Should Already Know–Before you continue you should have

a basic understanding of the following:•HTML and CSS

Page 5: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

5 /294

JS IntroductionWhat is JavaScript?• JavaScript was designed to add interactivity to

HTML pages• JavaScript is a scripting language• A scripting language is a lightweight programming

language• JavaScript is usually embedded directly into HTML

pages• JavaScript is an interpreted language (means that

scripts execute without preliminary compilation)• Everyone can use JavaScript without purchasing a

license

Page 6: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

6 /294

JS IntroductionAre Java and JavaScript the same?

• NO!• Java and JavaScript are two

completely different languages in both concept and design!

• Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++.

Page 7: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

7 /294

JS IntroductionWhat Can JavaScript do?

• JavaScript gives HTML designers a programming tool

–HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages.

Page 8: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

8 /294

JS IntroductionWhat Can JavaScript do?

• JavaScript can react to events –A JavaScript can be set to execute

when something happens, like when a page has finished loading or when a user clicks on an HTML element.

• JavaScript can manipulate HTML elements

–A JavaScript can read and change the content of an HTML element.

Page 9: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

9 /294

JS IntroductionWhat Can JavaScript do?• JavaScript can be used to validate data

–A JavaScript can be used to validate form input.• JavaScript can be used to detect the visitor's

browser –A JavaScript can be used to detect the visitor's

browser, and - depending on the browser - load another page specifically designed for that browser

• JavaScript can be used to create cookies –A JavaScript can be used to store and retrieve

information on the visitor's computer

Page 10: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

10 /294

JS IntroductionJavaScript = ECMAScript• JavaScript is an implementation of the ECMAScript

language standard. ECMA-262 is the official JavaScript standard.

• JavaScript was invented by Brendan Eich at Netscape (with Navigator 2.0), and has appeared in all browsers since 1996.

• The official standardization was adopted by the ECMA organization (an industry standardization association) in 1997.

• The ECMA standard (called ECMAScript-262) was approved as an international ISO (ISO/IEC 16262) standard in 1998.

• The development is still in progress.

Page 11: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

11 /294

JavaScript How ToManipulating HTML Elements

• The HTML <script> tag is used to insert a JavaScript into an HTML document.

• The HTML "id" attribute is used to identify HTML elements.

• JavaScript is typically used to manipulate existing HTML elements.

Page 12: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

12 /294

JavaScript How ToManipulating HTML Elements

• The HTML "id" attribute is used to identify HTML elements.

• To access an HTML element from a JavaScript, use the document.getElementById() method.

• The document.getElementById() method will access the HTML element with the specified id.

Page 13: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

13 /294

JavaScript How ToManipulating HTML Elements• Example

Access the HTML element with the specified id, and change its content:<!DOCTYPE html><html><body>

<h1>My First Web Page</h1>

<p id="demo">My First Paragraph</p>

<script type="text/javascript">document.getElementById("demo").innerHTML="My First JavaScript";</script>

</body></html>

Page 14: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

14 /294

JavaScript How ToManipulating HTML Elements• Example Explained• To insert a JavaScript into an HTML page,

use the <script> tag. • Inside the <script> tag use the type

attribute to define the scripting language.• The <script> and </script> tells where the

JavaScript starts and ends.• The lines between the <script> and

</script> contain the JavaScript and are executed by the browser:

Page 15: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

15 /294

JavaScript How ToManipulating HTML Elements• Example Explained• To insert a JavaScript into an HTML page, use the

<script> tag. • Inside the <script> tag use the type attribute to define

the scripting language.• The <script> and </script> tells where the JavaScript

starts and ends.• The lines between the <script> and </script> contain

the JavaScript and are executed by the browser• In this case, the browser will access the HTML

element with id="demo", and replace the content with "My First JavaScript".

Page 16: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

16 /294

JavaScript How ToSome Browsers do Not Support JavaScript

• Browsers that do not support JavaScript, will display JavaScript as page content.

• To prevent them from doing this, and as a part of the JavaScript standard, the HTML comment tag should be used to "hide" the JavaScript.

• Just add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end of comment) after the last JavaScript statement, like this:

Page 17: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

17 /294

JavaScript How ToSome Browsers do Not Support JavaScript

<!DOCTYPE html><html><body><script type="text/javascript"><!--document.getElementById("demo").innerHTML="My First JavaScript";//--></script></body></html>

The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents JavaScript from executing the --> tag.

Page 18: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

18 /294

JavaScript How ToWrite Directly into The HTML Document

• The example below writes a <p> element into the HTML document:• Example

<!DOCTYPE html><html>

<body>

<h1>My First Web Page</h1>

<script type="text/javascript">document.write("<p>My First JavaScript</p>");

</script>

</body></html>

The entire HTML page will be overwritten if document.write() is used inside a function

Page 19: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

19 /294

JavaScript Where ToJavaScript in <body>• The example below manipulate the content of an existing <p>

element when the page loads:• Example

<!DOCTYPE html><html><body><h1>My Web Page</h1><p id="demo">A Paragraph</p><script type="text/javascript">document.getElementById("demo").innerHTML="My First JavaScript";</script></body></html>

The JavaScript is placed at the bottom of the page to make sure it is not executed before the <p> element is created.

Page 20: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

20 /294

JavaScript Where ToJavaScript Functions and Events• The JavaScript statement in the example above,

is executed when the page loads, but that is not always what we want.

• Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button.

• Then we put the script inside a function.• Functions are normally used in combination

with events.• You will learn more about JavaScript functions

and events in later chapters.

Page 21: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

21 /294

JavaScript Where ToJavaScript Functions in <body>• This example also calls a function when a button is clicked, but the script

is placed at the bottom of the page:• Example

<!DOCTYPE html><html><body> <h1>My Web Page</h1><p id="demo">A Paragraph</p><button type="button" onclick="myFunction()">Try it</button><script type="text/javascript">function myFunction(){document.getElementById("demo").innerHTML="My First JavaScript Function";}</script></body></html>

Page 22: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

22 /294

JavaScript Where ToScripts in <head> and <body>

• You can place an unlimited number of scripts in your document, and you can have scripts in both the body and the head section at the same time.

• It is a common practice to put all functions in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.

Page 23: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

23 /294

JavaScript Where ToUsing an External JavaScript• JavaScript can also be placed in external files. • External JavaScript files often contain code to

be used on several different web pages. • External JavaScript files have the file

extension .js.• Note: External script cannot contain the

<script></script> tags!• To use an external script, point to the .js file

in the "src" attribute of the <script> tag:

Page 24: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

24 /294

JavaScript Where ToUsing an External JavaScript• Example

<!DOCTYPE html><html><body><script type="text/javascript" src="myScript.js"></script></body></html>

• Note: You can place the script in the head or body as you like.

• Note: The script will behave as it was located in the document, exactly where you put it.

Page 25: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

25 /294

JavaScript Statements

• JavaScript is a sequence of statements to be executed by the browser.

• JavaScript is Case SensitiveUnlike HTML, JavaScript is case sensitive - therefore watch your capitalization closely when you write JavaScript statements, create or call variables, objects and functions.

Page 26: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

26 /294

JavaScript Statements

• A JavaScript statement is a command to a browser. The purpose of the command is to tell the browser what to do.

• This JavaScript statement tells the browser to write "Hello Dolly" to an HTML element:

• document.getElementById("demo").innerHTML="Hello Dolly";• It is normal to add a semicolon at the end of each executable

statement. Most people think this is a good programming practice, and most often you will see this in JavaScript examples on the web.

• The semicolon is optional (according to the JavaScript standard), and the browser is supposed to interpret the end of the line as the end of the statement. Because of this you will often see examples without the semicolon at the end.

• Note: Using semicolons makes it possible to write multiple statements on one line.

Page 27: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

27 /294

JavaScript StatementsJavaScript Code• JavaScript code (or just JavaScript) is a sequence

of JavaScript statements.• Each statement is executed by the browser in the

sequence they are written.• This example will manipulate two HTML elements:• Example

document.getElementById("demo").innerHTML="Hello Dolly";document.getElementById("myDIV").innerHTML="How are you?";

Page 28: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

28 /294

JavaScript StatementsJavaScript Blocks• JavaScript statements can be grouped

together in blocks.• Blocks start with a left curly bracket {, and

end with a right curly bracket }.• The purpose of a block is to make the

sequence of statements execute together. • An example of statements grouped together

in blocks, are JavaScript functions. • This example will run a function that will

manipulate two HTML elements:

Page 29: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

29 /294

JavaScript StatementsJavaScript Blocks

• Examplefunction myFunction(){document.getElementById("demo").innerHTML="Hello Dolly";document.getElementById("myDIV").innerHTML="How are you?";}

Page 30: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

30 /294

JavaScript Comments

• JavaScript comments can be used to make the code more readable.

• Comments will not be executed by JavaScript.

• Comments can be added to explain the JavaScript, or to make the code more readable.

• Single line comments start with //.• The following example uses single line

comments to explain the code:

Page 31: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

31 /294

JavaScript Comments

• Example// Write to a heading:document.getElementById("myH1").innerHTML="Welcome to my Homepage";// Write to a paragraph:document.getElementById("myP").innerHTML="This is my first paragraph.";

Page 32: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

32 /294

JavaScript CommentsJavaScript Multi-Line Comments• Multi line comments start with /* and end with */.• The following example uses a multi line comment to

explain the code:• Example

/*The code below will writeto a heading and to a paragraph,and will represent the start ofmy homepage:*/document.getElementById("myH1").innerHTML="Welcome to my Homepage";document.getElementById("myP").innerHTML="This is my first paragraph.";

Page 33: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

33 /294

JavaScript CommentsUsing Comments to Prevent Execution• In the following example the comment is used to prevent the

execution of one of the codelines (can be suitable for debugging):• Example

//document.getElementById("myH1").innerHTML="Welcome to my Homepage";document.getElementById("myP").innerHTML="This is my first paragraph.";

• In the following example the comment is used to prevent the execution of a code block (can be suitable for debugging):

• Example/*document.getElementById("myH1").innerHTML="Welcome to my Homepage";document.getElementById("myP").innerHTML="This is my first paragraph.";*/

Page 34: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

34 /294

JavaScript CommentsUsing Comments at the End of a Line

• In the following example the comment is placed at the end of a code line:

• Examplevar x=5; // declare a variable and assign a value to itx=x+2; // Add 2 to the variable x

Page 35: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

35 /294

JavaScript Variables Do You Remember Algebra From School?

• Do you remember algebra from school? x=5, y=6, z=x+y

• Do you remember that a letter (like x) could be used to hold a value (like 5), and that you could use the information above to calculate the value of z to be 11?

• These letters are called variables, and variables can be used to hold values (x=5) or expressions (z=x+y).

• Variables are "containers" for storing information.

Page 36: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

36 /294

JavaScript Variables

• As with algebra, JavaScript variables are used to hold values or expressions.

• A variable can have a short name, like x, or a more descriptive name, like carname.

• Rules for JavaScript variable names:• Variable names are case sensitive (y and Y are two

different variables)• Variable names must begin with a letter, the $

character, or the underscore character• Note: Because JavaScript is case-sensitive,

variable names are case-sensitive.

Page 37: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

37 /294

JavaScript Variables Declaring (Creating) JavaScript Variables

• Creating a variable in JavaScript is most often referred to as "declaring" a variable.

• You declare JavaScript variables with the var keyword:var carname;

• After the declaration shown above, the variable is empty (it has no value yet).

• To assign a value to the variable, use the equal (=) sign:carname="Volvo";

Page 38: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

38 /294

JavaScript Variables Declaring (Creating) JavaScript Variables

• However, you can also assign a value to the variable when you declare it:var carname="Volvo";

• After the execution of the statement above, the carname will hold the value Volvo.

• To write the value inside an HTML element, simply refer to it by using it's variable name:

• Examplevar carname="Volvo";document.getElementById("myP").innerHTML=carname;

Page 39: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

39 /294

JavaScript Variables Declaring (Creating) JavaScript Variables

• Note: When you assign a text value to a variable, put quotes around the value.

• Note: When you assign a numeric value to a variable, do not put quotes around the value, if you put quotes around a numeric value, it will be treated as text.

• Note: If you redeclare a JavaScript variable, it will not lose its value.

Page 40: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

40 /294

JavaScript Variables Local JavaScript Variables

• A variable declared within a JavaScript function becomes LOCAL and can only be accessed within that function. (the variable has local scope).

• You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.

• Local variables are deleted as soon as the function is completed.

• You will learn more about functions in a later chapter of this tutorial.

Page 41: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

41 /294

JavaScript Variables Global JavaScript Variables

• Variables declared outside a function, become GLOBAL, and all scripts and functions on the web page can access it.

• Global variables are deleted when you close the page.

Page 42: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

42 /294

JavaScript VariablesAssigning Values to Undeclared JavaScript Variables

• If you assign values to variables that have not yet been declared, the variables will automatically be declared as global variables.

• This statement:carname="Volvo";

• will declare the variable carname as a global variable (if it does not already exist).

Page 43: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

43 /294

JavaScript Data TypesJavaScript is Weakly Typed

• String, Number, Boolean, Array, Object, Null, Undefined.

• JavaScript is weakly typed. This means that the same variable can be used as different types:

• Examplevar x // Now x is undefinedvar x = 5; // Now x is a Numbervar x = "John"; // Now x is a String

Page 44: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

44 /294

JavaScript Data TypesString

• A string is a variable which stores a series of characters like "John Doe".

• A string can be any text inside quotes. You can use simple or double quotes:

• Examplevar carname="Volvo XC60";var carname='Volvo XC60';

• You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

• Examplevar answer="It's alright";var answer="He is called 'Johnny'";var answer='He is called "Johnny"';

Page 45: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

45 /294

JavaScript Data TypesNumbers

• JavaScript has only one type of numbers. Numbers can be written with, or without decimals:

• Examplevar x1=34.00; //Written with decimalsvar x2=34; //Written without decimals

• Extra large or extra small numbers can be written with scientific (exponential) notation:

• Examplevar y=123e5; // 12300000var z=123e-5; // 0.00123

Page 46: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

46 /294

JavaScript Data TypesBooleans

• Booleans can only have two values: true or false.

var x=truevar y=false

• Booleans are often used in conditional testing. You will learn more about conditional testing in a later chapter of this tutorial.

Page 47: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

47 /294

JavaScript Data TypesArrays

• The following code creates an Array called cars:var cars=new Array();cars[0]="Saab";cars[1]="Volvo";cars[2]="BMW";

• or (condensed array):var cars=new Array("Saab","Volvo","BMW");

• or (literal array):• Example

var cars=["Saab","Volvo","BMW"];• Array indexes are zero-based, which means the first

item is [0], second is [1], and so on.

Page 48: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

48 /294

JavaScript Data TypesObjects

• An object is delimited by curly braces. Inside the braces the object's properties are defined as name and value pairs (name : value). The properties are separated by commas:var person={firstname:"John", lastname:"Doe", id:5566};

• The object (person) in the example above has 3 properties: firstname, lastname, and id.

Page 49: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

49 /294

JavaScript Data TypesObjects

• Spaces and line breaks are not important. Your declaration can span multiple lines:var person={firstname : "John",lastname : "Doe",id : 5566};

• You can address the object properties in two ways:• Example

name=person.lastname;name=person["lastname"];

Page 50: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

50 /294

JavaScript Data TypesUndefined and Null

• Undefined is the value of a variable with no value.• Variables can be emptied by setting the value

to null;• Example

cars=null;person=null;

Page 51: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

51 /294

JavaScript Data TypesDeclaring Variable Types

• When you declare a new variable, you can declare its type using the "new" keyword:var carname=new String;var x= new Number;var y= new Boolean;var cars= new Array;var person= new Object;

• JavaScript variables are all objects. When you declare a variable you create a new object.

Page 52: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

52 /294

JavaScript Operators JavaScript Arithmetic Operators

• Given that y=5, the table below explains the arithmetic operators:

Page 53: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

53 /294

JavaScript OperatorsJavaScript Assignment Operators

• Given that x=10 and y=5, the table below explains the assignment operators:

Page 54: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

54 /294

JavaScript OperatorsThe + Operator Used on Strings

• The + operator can also be used to add string variables or text values together.

• Example• To add two or more string variables

together, use the + operator.txt1="What a very ";txt2="nice day";txt3=txt1+txt2;

• The result of txt3 will be:What a very nice day

Page 55: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

55 /294

JavaScript OperatorsAdding Strings and Numbers

• Adding two numbers, will return the sum, but adding a number and a string will return a string:

• Examplex=5+5;y="5"+5;z="Hello"+5;

• The result of x,y, and z will be:1055Hello5

The rule is: If you add a number and a string, the result will be a string!

Page 56: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

56 /294

JavaScript OperatorsComparison Operators

• Comparison operators are used in logical statements to determine equality or difference between variables or values.

• Given that x=5, the table below explains the comparison operators:

Page 57: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

57 /294

JavaScript OperatorsComparison Operators

• How Can it be Used• Comparison operators can be used in conditional

statements to compare values and take action depending on the result:if (age<18) x="Too young";

• You will learn more about the use of conditional statements in the next chapter of this tutorial.

Page 58: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

58 /294

JavaScript Operators Logical Operators

• Logical operators are used to determine the logic between variables or values.

• Given that x=6 and y=3, the table below explains the logical operators:

Page 59: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

59 /294

JavaScript OperatorsConditional Operator

• JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

• Syntaxvariablename=(condition)?value1:value2

• Example• Example• If the variable age is a value below 18, the value of

the variable voteable will be "Too young, otherwise the value of voteable will be "Old enough":voteable=(age<18)?"Too young":"Old enough";

Page 60: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

60 /294

JavaScript Flow ControlIf...Else Statements

• Use the if....else statement to execute some code if a condition is true and another code if the condition is not true.

• Syntaxif (condition) {  code to be executed if condition is true }else {  code to be executed if condition is not true }

Page 61: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

61 /294

JavaScript Flow ControlIf...Else Statements

• Example• If the time is less than 20:00, you will get a "Good day"

greeting, otherwise you will get a "Good evening" greetingif (time<20) { x="Good day"; }else { x="Good evening"; }

• The result of x will be:Good day

Page 62: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

62 /294

JavaScript Flow ControlIf...else if...else Statement

• Use the if....else if...else statement to select one of several blocks of code to be executed.

• Syntaxif (condition1) {  code to be executed if condition1 is true }else if (condition2) {  code to be executed if condition2 is true }else {  code to be executed if neither condition1 nor condition2 is true }

Page 63: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

63 /294

JavaScript Flow ControlIf...else if...else Statement

• Example• If the time is less than 10:00, you will get a "Good morning" greeting, if not, but

the time is less than 20:00, you will get a "Good day" greeting, otherwise you will get a "Good evening" greeting:if (time<10) { x="Good morning"; }else if (time<20) { x="Good day"; }else { x="Good evening"; }

• The result of x will be:Good day

Page 64: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

64 /294

JavaScript Flow ControlSwitch Statement

• Use the switch statement to select one of many blocks of code to be executed.

• Syntaxswitch(n){case 1:  execute code block 1 break;case 2:  execute code block 2 break;default:  code to be executed if n is different from case 1 and 2}

Page 65: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

65 /294

JavaScript Flow ControlSwitch Statement

• This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically.

• Use the default keyword to specify what to do if there is no match.

Page 66: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

66 /294

JavaScript Popup BoxesAlert Box

• Use the default keyword to specify what to do if there is no match:

• An alert box is often used if you want to make sure information comes through to the user.

• When an alert box pops up, the user will have to click "OK" to proceed.

• Syntaxalert("sometext");

Page 67: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

67 /294

JavaScript Popup BoxesAlert Box

Example<!DOCTYPE html><html><head><script type="text/javascript">function myFunction(){alert("I am an alert box!");}</script></head><body>

<input type="button" onclick="myFunction()" value="Show alert box" />

</body></html>

Page 68: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

68 /294

JavaScript Popup BoxesConfirm Box

• A confirm box is often used if you want the user to verify or accept something.

• When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.

• If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

• Syntaxconfirm("sometext");

Page 69: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

69 /294

JavaScript Popup BoxesConfirm Box

• A confirm box is often used if you want the user to verify or accept something.

• When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.

• If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

• Syntaxconfirm("sometext");

Page 70: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

70 /294

JavaScript Popup BoxesConfirm Box

• Examplevar r=confirm("Press a button");if (r==true) { x="You pressed OK!"; }else { x="You pressed Cancel!"; }

Page 71: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

71 /294

JavaScript Popup BoxesPrompt Box

• A prompt box is often used if you want the user to input a value before entering a page.

• When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.

• If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.

• Syntaxprompt("sometext","defaultvalue");

Page 72: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

72 /294

JavaScript Popup BoxesPrompt Box

• Examplevar name=prompt("Please enter your name","Harry Potter");if (name!=null && name!="") { x="Hello " + name + "! How are you today?"; }

Page 73: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

73 /294

JavaScript Popup BoxesLine Breaks

• To display line breaks inside a popup box, use a back-slash followed by the character n.

• Examplealert("Hello\nHow are you?");

Page 74: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

74 /294

JavaScript Functions

• A function is a block of code that executes only when you tell it to execute.

• A function can be executed by an event, like clicking a button.

• It can be when an event occurs, like when a user clicks a button, or from a call within your script, or from a call within another function.

• Functions can be placed both in the <head> and in the <body> section of a document, just make sure that the function exists, when the call is made.

Page 75: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

75 /294

JavaScript Functions How to Define a Function

• Syntaxfunction functionname(){some code}

• The { and the } defines the start and end of the function.

• Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name.

Page 76: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

76 /294

JavaScript FunctionsJavaScript Function Example

<!DOCTYPE html><html><head><script type="text/javascript">function myFunction(){alert("Hello World!");}</script></head>

<body><button onclick="myFunction()">Try it</button></body></html>

The function is executed when the user clicks the button.You will learn more about JavaScript events in the JS Events chapter.

Page 77: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

77 /294

JavaScript FunctionsCalling a Function with Arguments

• When you call a function, you can pass along some values to it, these values are called arguments or parameters.

• Theese arguments can be used inside the function.• You can send as many arguments as you like,

separated by commas (,)myFunction(argument1,argument2)

• Declare the argument, as variables, when you declare the function: function myFunction(var1,var2){some code}

Page 78: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

78 /294

JavaScript FunctionsCalling a Function with Arguments

• The variables and the arguments must be in the expected order. The first variable is given the value of the first passed argument etc.

• Example<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

<script type="text/javascript">function myFunction(name,job){alert("Welcome " + name + ", the " + job);}</script>

Page 79: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

79 /294

JavaScript FunctionsCalling a Function with Arguments

• The function above will alert "Welcome Harry Potter, the Wizard" when the button is clicked.

• The function is flexible, you can call the function using different arguments, and different welcome messages will be given:

• Example<button onclick="myFunction('Harry Potter','Wizard')">Try it</button><button onclick="myFunction('Bob','Builder')">Try it</button>

• The example above will alert "Welcome Harry Potter, the Wizard" or "Welcome Bob, the Builder" depending on which button is clicked.

Page 80: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

80 /294

JavaScript FunctionsFunctions With a Return Value

• Sometimes you want your function to return a value back to where the call was made.

• This is possible by using the return statement.• When using the return statement, the function will

stop executing, and return the specified value.• Syntax

function myFunction(){var x=5;return x;}

Page 81: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

81 /294

JavaScript FunctionsFunctions With a Return Value

• The function above will return the value 5.• Note: It is not the entire JavaScript that will stop

executing, only the function. JavaScript will continue executing code, where the function-call was made from.

• The function-call will be replaced with the returnvalue:var myVar=myFunction();

• The variable myVar holds the value 5, which is what the function "myFunction()" returns.

Page 82: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

82 /294

JavaScript FunctionsFunctions With a Return Value

• You can also use the returnvalue without storing it as a variable:

document.getElementById("demo").innerHTML=myFunction();

• The innerHTML of the "demo" element will be 5, which is what the function "myFunction()" returns.

• You can make a returnvalue based on arguments passed into the function:

Page 83: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

83 /294

JavaScript FunctionsFunctions With a Return Value

• Example• Calculate the product of two numbers, and return the

result:function myFunction(a,b){return a*b;}

document.getElementById("demo").innerHTML=myFunction(4,3);

• The innerHTML of the "demo" element will be:12

Page 84: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

84 /294

JavaScript FunctionsFunctions With a Return Value

• The return statement is also used when you simply want to exit a function. The return value is optional:function myFunction(a,b){if (a>b) { return; }x=a+b}

• The function above will exit the function if a>b, and will not calculate the sum of a and b.

Page 85: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

85 /294

JavaScript FunctionsThe Lifetime of JavaScript Variables

• If you declare a variable, using "var", within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared.

• If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.

Page 86: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

86 /294

JavaScript Loops

• Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.

• In JavaScript, there are two different kind of loops:• for - loops through a block of code a specified

number of times• while - loops through a block of code while a

specified condition is true

Page 87: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

87 /294

JavaScript LoopsThe for Loop

• The for loop is used when you know in advance how many times the script should run.

• For Loops will execute a block of code a specified number of times.

• Syntaxfor (variable=startvalue;variable<endvalue;variable=variable+increment) {  code to be executed }

Page 88: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

88 /294

JavaScript LoopsThe for Loop

• Example• The example below defines a loop that starts with

i=0. The loop will continue to run as long as i is less than 5. i will increase by 1 each time the loop runs.

• Note: The increment parameter could also be negative, and the < could be any comparing statement.

• Examplefor (i=0; i<5; i++) { x=x + "The number is " + i + "<br />"; }

Page 89: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

89 /294

JavaScript LoopsThe while Loop

• While Loops execute a block of code as long as a specified condition is true.

• Syntaxwhile (variable<endvalue) {  code to be executed }

• Note: The < could be any comparing operator.

Page 90: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

90 /294

JavaScript LoopsThe while Loop

• Example• The example below defines a loop that starts with

i=0. The loop will continue to run as long as i is less than 5. i will increase by 1 each time the loop runs:

• Examplewhile (i<5) { x=x + "The number is " + i + "<br />"; i++; }

• Note: Do not forget to increase the i variable used in the condition, otherwise i will always be less than 5, and the loop will never end!

Page 91: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

91 /294

JavaScript LoopsThe do...while Loop

• The do...while loop is a variant of the while loop. This loop will execute the block of code once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

• Syntaxdo {  code to be executed  }while (variable<endvalue);

Page 92: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

92 /294

JavaScript LoopsThe do...while Loop

• Example• The example below uses a do...while loop. The

do...while loop will always be executed at least once, even if the condition is false, because the statements are executed before the condition is tested:

• Exampledo { x=x + "The number is " + i + "<br />"; i++; }while (i<5);

Note: Do not forget to increase the i variable used in the condition, otherwise i will always be less than 5,

and the loop will never end!

Page 93: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

93 /294

JavaScript Break and Continue StatementsThe break Statement

• The break statement will break the loop and continue executing the code that follows after the loop (if any).

• Examplefor (i=0;i<10;i++) { if (i==3) { break; } x=x + "The number is " + i + "<br />"; }

Result:The number is 0The number is 1The number is 2

Page 94: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

94 /294

JavaScript Break and Continue StatementsThe continue Statement

• The continue statement will break the current loop and continue with the next value.

• Examplefor (i=0;i<=10;i++) { if (i==3) { continue; } x=x + "The number is " + i + "<br />"; }

Result:The number is 0The number is 1The number is 2The number is 4The number is 5The number is 6The number is 7The number is 8The number is 9

Page 95: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

95 /294

JavaScript For...In Statement

• The for...in statement loops through the properties of an object.

• Syntaxfor (variable in object) {  code to be executed }

• Note: The block of code inside of the for...in loop will be executed once for each property.

Page 96: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

96 /294

JavaScript For...In Statement

• Example• Looping through the properties of an object:• Example

var person={fname:"John",lname:"Doe",age:25};

for (x in person) { txt=txt + person[x]; }

Page 97: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

97 /294

JavaScript Events

• By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript.

• Every element on a web page has certain events which can trigger a JavaScript. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags.

Page 98: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

98 /294

JavaScript Events

• Examples of events:–A mouse click–A web page or an image loading–Mousing over a hot spot on the web page–Selecting an input field in an HTML form–Submitting an HTML form–A keystroke

• Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs!

Page 99: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

99 /294

JavaScript EventsonLoad and onUnload

• The onLoad and onUnload events are triggered when the user enters or leaves the page.

• The onLoad event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.

Page 100: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

100 /294

JavaScript EventsonLoad and onUnload

• Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!".

Page 101: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

101 /294

JavaScript EventsonFocus, onBlur and onChange

• The onFocus, onBlur and onChange events are often used in combination with validation of form fields.

• Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user changes the content of the field:<input type="text" size="30" id="email" onchange="checkEmail()" />

Page 102: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

102 /294

JavaScript EventsonSubmit

• The onSubmit event is used to validate ALL form fields before submitting it.

• Below is an example of how to use the onSubmit event. The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled:<form method="post" action="which.php" onsubmit="return checkForm()">

Page 103: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

103 /294

JavaScript Try...Catch Statement

• When browsing Web pages on the internet, we all have seen a JavaScript alert box telling us there is a runtime error and asking "Do you wish to debug?". Error message like this may be useful for developers but not for users. When users see errors, they often leave the Web page.

• The try...catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs.

Page 104: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

104 /294

JavaScript Try...Catch Statement

• Syntaxtry { //Run some code here }catch(err) { //Handle errors here }

• Note that try...catch is written in lowercase letters. Using uppercase letters will generate a JavaScript error!

Page 105: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

105 /294

JavaScript Try...Catch StatementExample

• The example below is supposed to alert "Welcome guest!" when the button is clicked. However, there's a typo in the message() function. alert() is misspelled as adddlert(). A JavaScript error occurs. The catch block catches the error and executes a custom code to handle it. The code displays a custom error message informing the user what happened:

Page 106: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

106 /294

JavaScript Try...Catch StatementExamples

function message(){try { adddlert("Welcome guest!"); }catch(err) { txt="There was an error on this page.\n\n"; txt+="Error description: " + err.message + "\n\n"; txt+="Click OK to continue.\n\n"; alert(txt); }}

Page 107: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

107 /294

JavaScript Throw Statement

• The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages.

• Syntaxthrow exception

• The exception can be a string, integer, Boolean or an object.

• Note that throw is written in lowercase letters. Using uppercase letters will generate a JavaScript error!

Page 108: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

108 /294

JavaScript Throw StatementExample

• The example below determines the value of a variable called x. If the value of x is higher than 10, lower than 5, or not a number, we are going to throw an error. The error is then caught by the catch argument and the proper error message is displayed:

Page 109: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

109 /294

JavaScript Throw StatementExample

var x=prompt("Enter a number between 5 and 10:","");try { if(x>10) { throw "Err1"; } else if(x<5) { throw "Err2"; } else if(isNaN(x)) { throw "Err3"; } }

catch(err) { if(err=="Err1") { document.write("Error! The value is too high."); } if(err=="Err2") { document.write("Error! The value is too low."); } if(err=="Err3") { document.write("Error! The value is not a number."); } }

Page 110: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

110 /294

JavaScript Special Characters

• The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters into a text string.

• Look at the following JavaScript code:• var txt="We are the so-called "Vikings" from the

north.";document.write(txt);

• In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to: We are the so-called

Page 111: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

111 /294

JavaScript Special Characters

• To solve this problem, you must place a backslash (\) before each double quote in "Viking". This turns each double quote into a string literal:

• var txt="We are the so-called \"Vikings\" from the north.";document.write(txt);

• JavaScript will now output the proper text string: We are the so-called "Vikings" from the north.

• The table below lists other special characters that can be added to a text string with the backslash sign:

Page 112: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

112 /294

JavaScript Special Characters

Page 113: Java Script Tutorial

JS HTML DOM

DOM IntroDOM HTMLDOM CSSDOM EventsDOM Nodes

Page 114: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM IntroThe HTML DOM

• Document Object Model• With the HTML DOM, JavaScript can

access all the elements of an HTML document.

• When a web page is loaded, the browser creates a Document Object Model of the page.

• The HTML DOM model is constructed as a tree of Objects:

114 /171

Page 115: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM IntroThe HTML DOM

115 /171

Page 116: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM IntroThe HTML DOM• With a programmable object model, JavaScript

gets all the power it needs to create dynamic HTML:

• JavaScript can change all the HTML elements in the page

• JavaScript can change all the HTML attributes in the page

• JavaScript can change all the CSS styles in the page

• JavaScript can react to all the events in the page

116 /171

Page 117: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM IntroFinding HTML Elements

• Often, with JavaScript, you want to manipulate HTML elements.

• To do so, you have to find the elements first. There are a couple of ways to do this:

–Finding HTML elements by id–Finding HTML elements by tag name–Finding HTML elements by class

name117 /171

Page 118: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM IntroFinding HTML Elements by Id• The easiest way to find HTML elements in

the DOM, is by using the element id.• This example finds the element with

id="intro":• Example

var x=document.getElementById("intro");If the element is found, the method will return the element as an object (in x).

• If the element is not found, x will contain null.

118 /171

Page 119: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM IntroFinding HTML Elements by Tag Name

• This example finds the element with id="main", and then finds all <p> elements inside "main":

• Examplevar x=document.getElementById("main");var y=x.getElementsByTagName("p");Finding elements by class name does not work in Internet Explorer 5,6,7, and 8.

119 /171

Page 120: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM HTMLChanging HTML - Output

• The HTML DOM allows JavaScript to change the content of HTML elements.

• JavaScript can create dynamic HTML content:• Date: Mon Oct 29 2012 22:24:02 GMT+0330

(Iran Standard Time)• In JavaScript, document.write() can be used

to write directly to the HTML output stream .• Never use document.write() after the

document is loaded. It will overwrite the document.

120 /171

Page 121: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM HTMLChanging HTML - Content• The easiest way to modify the content of an HTML element is by

using the innerHTML property.• To change the content of an HTML element, use this syntax:• document.getElementById(id).innerHTML=new HTML• This example changes the content of a <p> element:• Example

<html><body>

<p id="p1">Hello World!</p>

<script>document.getElementById("p1").innerHTML="New text!";</script>

</body></html>121 /171

Page 122: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM HTMLChanging HTML - Content• This example changes the content of an <h1> element:• Example

<!DOCTYPE html><html><body>

<h1 id="header">Old Header</h1>

<script>var element=document.getElementById("header");element.innerHTML="New Header";</script>

</body></html>

122 /171

Page 123: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM HTMLChanging HTML - HTML Attribute• To change the attribute of an HTML element, use this syntax:

document.getElementById(id).attribute=new value• This example changes the src attribute of an <img> element:• Example

<!DOCTYPE html><html><body>

<img id="image" src="smiley.gif">

<script>document.getElementById("image").src="landscape.jpg";</script>

</body></html>

123 /171

Page 124: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM CSSChanging CSS• The HTML DOM allows JavaScript to change the style of HTML elements.

• To change the style of an HTML element, use this syntax:• document.getElementById(id).style.property=new style• The following example changes the style of a <p> element:• Example

<html><body>

<p id="p2">Hello World!</p>

<script>document.getElementById("p2").style.color="blue";</script>

<p>The paragraph above was changed by a script.</p>

</body></html>124 /171

Page 125: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM CSSChanging CSS• This example changes the style of the HTML element with

id="id1", when the user clicks a button:• Example

<!DOCTYPE html><html><body>

<h1 id="id1">My Heading 1</h1><button type="button" onclick="document.getElementById('id1').style.color='red'">Click Me!</button>

</body></html>

125 /171

Page 126: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM HTMLDOM Nodes• In the HTML DOM, everything is a node. The DOM is

HTML viewed as a node tree.• According to the W3C HTML DOM standard,

everything in an HTML document is a node:–The entire document is a document node–Every HTML element is an element node–The text inside HTML elements are text nodes–Every HTML attribute is an attribute node–Comments are comment nodes

• With the HTML DOM, all nodes in the tree can be accessed by JavaScript. All HTML elements (nodes) can be modified, and nodes can be created or deleted.

126 /171

Page 127: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM HTMLNode Parents, Children, and Siblings

• The nodes in the node tree have a hierarchical relationship to each other.

• The terms parent, child, and sibling are used to describe the relationships. Parent nodes have children. Children on the same level are called siblings (brothers or sisters).

–In a node tree, the top node is called the root–Every node has exactly one parent, except the root

(which has no parent)–A node can have any number of children–Siblings are nodes with the same parent

127 /171

Page 128: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM HTMLNode Parents, Children, and Siblings

• The following image illustrates a part of the node tree and the relationship between the nodes:

128 /171

Page 129: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM HTMLNode Parents, Children, and Siblings• Look at the following HTML fragment:

<html> <head> <title>DOM Tutorial</title> </head> <body> <h1>DOM Lesson one</h1> <p>Hello world!</p> </body></html>

129 /171

Page 130: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM HTMLNode Parents, Children, and Siblings• From the HTML above:• The <html> node has no parent node; it is the root node• The parent node of the <head> and <body> nodes is the <html> node• The parent node of the "Hello world!" text node is the <p> nodeand:• The <html> node has two child nodes: <head> and <body>• The <head> node has one child node: the <title> node• The <title> node also has one child node: the text node "DOM

Tutorial"• The <h1> and <p> nodes are siblings and child nodes of <body>and:• The <head> element is the first child of the <html> element• The <body> element is the last child of the <html> element• The <h1> element is the first child of the <body> element• The <p> element is the last child of the <body> element130 /171

Page 131: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript DOM HTMLWarning !

• A common error in DOM processing is to expect an element node to contain text.

• In this example: <title>DOM Tutorial</title>, the element node <title>, holds a text node with the value "DOM Tutorial".

• The value of the text node can be accessed by the node's innerHTML property.

• You will read more about the innerHTML property in a later chapter.

131 /171

Page 132: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM MethodsProgramming Interface

• Methods are actions you can perform on nodes (HTML Elements).

• The HTML DOM can be accessed with JavaScript (and other programming languages).

• All HTML elements are defined as objects, and the programming interface is the object methods and object properties .

• A method is an action you can do (like add or modify an element).

• A property is a value that you can get or set (like the name or content of a node).

132 /171

Page 133: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM MethodsHTML DOM Objects - Methods and Properties

• Some commonly used HTML DOM methods:– getElementById(id) - get the node (element) with a

specified id– appendChild(node) - insert a new child node (element)– removeChild(node) - remove a child node (element)

• Some commonly used HTML DOM properties:– innerHTML - the text value of a node (element)– parentNode - the parent node of a node (element)– childNodes - the child nodes of a node (element)– attributes - the attributes nodes of a node (element)– You will learn more about properties in the next

chapter of this tutorial.

133 /171

Page 134: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM MethodsA Real Life Object Illustration

• A person is an object.• A person's methods could be eat(), sleep(), work(),

play(), etc.• All persons have these methods, but they are

performed at different times.• A person's properties include name, height,

weight, age, eye color, etc.• All persons have these properties, but their values

differ from person to person.

134 /171

Page 135: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM MethodsSome DOM Object Methods

• Here are some of the (most common) methods you will learn about in this tutorial:

• getElementById() : Returns the element that has an ID attribute with the a value.

• getElementsByTagName() : Returns a node list (collection/array of nodes) containing all elements with a specified tag name.

• getElementsByClassName() : Returns a node list containing all elements with a specified class.

• appendChild() : Adds a new child node to a specified node

• removeChild() : Removes a child node .135 /171

Page 136: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM MethodsSome DOM Object Methods

• replaceChild() : Replaces a child node .• insertBefore() : Inserts a new child node before a

specified child node .• createAttribute() : Creates an Attribute node.• createElement() : Creates an Element node.• createTextNode() : Creates a Text node .• getAttribute() : Returns the specified attribute

value .• setAttribute() : Sets or changes the specified

attribute, to the specified value .

136 /171

Page 137: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM PropertiesThe nodeName Property

• The nodeName property specifies the name of a node.

–nodeName is read-only.–nodeName of an element node is the same as the

tag name.–nodeName of an attribute node is the attribute

name.–nodeName of a text node is always #text.–nodeName of the document node is always

#document.

•Note: nodeName always contains the uppercase tag name of an HTML element.

137 /171

Page 138: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM PropertiesThe nodeValue Property

• The nodeValue property specifies the value of a node.

–nodeValue for element nodes is undefined–nodeValue for text nodes is the text itself–nodeValue for attribute nodes is the

attribute value

138 /171

Page 139: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM PropertiesGet the Value of an Element

• The following example retrieves the text node value of the <p id="intro"> tag:

• Example<html><body>

<p id="intro">Hello World!</p>

<script type="text/javascript">x=document.getElementById("intro");document.write(x.firstChild.nodeValue);</script>

</body></html>

139 /171

Page 140: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM PropertiesThe nodeType Property

• The nodeType property returns the type of node. nodeType is read only.

• The most important node types are:

140 /171

Page 141: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM ElementsCreating New HTML Elements - appendChild()

• To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.

• Example<div id="d1"><p id="p1">This is a paragraph.</p><p id="p2">This is another paragraph.</p></div>

<script>var para=document.createElement("p");var node=document.createTextNode("This is new.");para.appendChild(node);

var element=document.getElementById("d1");element.appendChild(para);</script>

141 /171

Page 142: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM ElementsCreating New HTML Elements - appendChild()

• Example Explained • This code creates a new <p> element:

var para=document.createElement("p");• To add text to the <p> element, you must

create a text node first. This code creates a text node:var node=document.createTextNode("This is a new paragraph.");

• Then you must append the text node to the <p> element:para.appendChild(node);

142 /171

Page 143: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM ElementsCreating New HTML Elements - appendChild()

• Finally you must append the new element to an existing element.

• This code finds an existing element:var element=document.getElementById("d1");

• This code appends the new element to the existing element:element.appendChild(para);

143 /171

Page 144: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM Elements Creating new HTML Elements - insertBefore()

• The appendChild() method in the previous example, appended the new element as the last child of the parent.

• If you don't want that you can use the insertBefore() method:

144 /171

Page 145: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM Elements Creating new HTML Elements - insertBefore()

• Example<div id="d1"><p id="p1">This is a paragraph.</p><p id="p2">This is another paragraph.</p></div>

<script>var para=document.createElement("p");var node=document.createTextNode("This is new.");para.appendChild(node);

var element=document.getElementById("d1");var child=document.getElementById("p1");element.insertBefore(para,child);</script>

145 /171

Page 146: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM ElementsRemoving Existing HTML Elements

• To remove an HTML element, you must know the parent of the element:

• Example<div id="d1"><p id="p1">This is a paragraph.</p><p id="p2">This is another paragraph.</p></div> <script>var parent=document.getElementById("d1");var child=document.getElementById("p1");parent.removeChild(child);</script>

146 /171

Page 147: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM ElementsRemoving Existing HTML Elements

• Example Explained • This HTML document contains a <div> element

with two child nodes (two <p> elements):<div id="d1"><p id="p1">This is a paragraph.</p><p id="p2">This is another paragraph.</p></div>

• Find the <div> element with id="id1":var parent=document.getElementById("d1");

• Find the <p> element with id="p1":var child=document.getElementById("p1");

147 /171

Page 148: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM ElementsRemoving Existing HTML Elements

• Remove the child from the parent:parent.removeChild(child);

• Q : Would it be nice to be able to remove an element without referring to the parent?A : Sorry. The DOM need to know both the element you want to remove, and its parent.

• Here is a common workaround: Find the child you want to remove, and use its parentNode property to find the parent:var child=document.getElementById("p1");child.parentNode.removeChild(child);

148 /171

Page 149: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM ElementsReplacing HTML Elements

• To replace an element to the HTML DOM, use the replaceChild() method:• Example

<div id="d1"><p id="p1">This is a paragraph.</p><p id="p2">This is another paragraph.</p></div>

<script>var para=document.createElement("p");var node=document.createTextNode("This is new.");para.appendChild(node);

var parent=document.getElementById("d1");var child=document.getElementById("p1");parent.replaceChild(para,child);</script>

149 /171

Page 150: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM EventsHTML Event Attributes

• To assign events to HTML elements you can use event attributes.

• Example• Assign an onclick event to a button

element:<button onclick="displayDate()">Try it</button>

• In the example above, a function named displayDate will be executed when the button is clicked.

150 /171

Page 151: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM EventsAssign Events Using the HTML DOM

• The HTML DOM allows you to assign events to HTML elements using JavaScript:

• Example• Assign an onclick event to a button element:

<script>document.getElementById("myBtn").onclick=function(){displayDate()};</script>

• In the example above, a function named displayDate is assigned to an HTML element with the id=myButn".

• The function will be executed when the button is clicked.

151 /171

Page 152: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM EventsThe onchange Event

• The onchange event are often used in combination with validation of input fields.

• Below is an example of how to use the onchange. The upperCase() function will be called when a user changes the content of an input field.

• Example<input type="text" id="fname" onchange="upperCase()">

152 /171

Page 153: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM EventsMouse Events

• onmouseover• onmouseout• onmousedown• onmouseup• onclick

153 /171

Page 154: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM Navigation HTML DOM Node List

• With the HTML DOM, you can navigate the node tree using node relationships.

• The getElementsByTagName() method returns a node list. A node list is an array of nodes.

• The following code selects all <p> nodes in a document:

• Examplevar x=document.getElementsByTagName("p");

• The nodes can be accessed by index number. To access the second <p> you can write:y=x[1];

• Note: The index starts at 0.154 /171

Page 155: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM Navigation HTML DOM Node List Length

• The length property defines the number of nodes in a node-list.

• You can loop through a node-list by using the length property:• Example

x=document.getElementsByTagName("p");

for (i=0;i<x.length;i++){document.write(x[i].innerHTML);document.write("<br />");}

• Example explained:• Get all <p> element nodes• For each <p> element, output the value of its text node

155 /171

Page 156: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM Navigation Navigating Node Relationships

• You can use the three node properties; parentNode, firstChild, and lastChild, to navigate in the document structure.

• Look at the following HTML fragment:<html><body>

<p>Hello World!</p><div> <p>The DOM is very useful!</p> <p>This example demonstrates node relationships.</p></div>

</body></html>

156 /171

Page 157: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM Navigation Navigating Node Relationships

• You can use the three node properties; parentNode, firstChild, and lastChild, to navigate in the document structure.

• Look at the following HTML fragment:<html><body>

<p>Hello World!</p><div> <p>The DOM is very useful!</p> <p>This example demonstrates node relationships.</p></div>

</body></html>

157 /171

Page 158: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM Navigation Navigating Node Relationships

• The first <p> element is the firstChild of the <body> element

• The <div> element is the lastChild of the <body> element

• The <body> element is the parentNode of the first <p> element and the <div> element

• The firstChild property can be used to access the text of an element:

158 /171

Page 159: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM Navigation Navigating Node Relationships

• Example<html><body>

<p id="intro">Hello World!</p>

<script>x=document.getElementById("intro");document.write(x.firstChild.nodeValue);</script>

</body></html>

159 /171

Page 160: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM NavigationDOM Root Nodes

• There are two special properties that allow access to the full document:

• document.documentElement - The full document

• document.body - The body of the document

160 /171

Page 161: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM NavigationDOM Root Nodes

• Example<html><body>

<p>Hello World!</p><div><p>The DOM is very useful!</p><p>This example demonstrates the <b>document.body</b> property.</p></div>

<script>alert(document.body.innerHTML);</script>

</body></html>161 /171

Page 162: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM NavigationchildNodes and nodeValue

• In addition to the innerHTML property, you can also use the childNodes and nodeValue properties to get the content of an element.

• The following code gets the value of the <p> element with id="intro":

162 /171

Page 163: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM NavigationchildNodes and nodeValue

• Example<html><body>

<p id="intro">Hello World!</p>

<script>var txt=document.getElementById("intro").childNodes[0].nodeValue;document.write(txt);</script>

</body></html>163 /171

Page 164: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

JavaScript HTML DOM NavigationchildNodes and nodeValue

• In the example above, getElementById is a method, while childNodes and nodeValue are properties.

• In this tutorial we will use the innerHTML property. However, learning the method above is useful for understanding the tree structure and the navigation of the DOM.

164 /171

Page 165: Java Script Tutorial

JS Objects

JS Objects IntroJS StringJS DateJS ArrayJS BooleanJS MathJS RegExp

Page 166: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

166 /294

JavaScript Objects Introduction

• JavaScript is an Object Based Programming language.

• An Object Based Programming language allows you to define your own objects and make your own variable types.

Page 167: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

167 /294

JavaScript Objects IntroductionObject Based Programming

• However, creating your own objects will be explained later, in the Advanced JavaScript section. We will start by looking at the built-in JavaScript objects, and how they are used.

• Note that an object is just a special kind of data. An object has properties and methods.

Page 168: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

168 /294

JavaScript Objects IntroductionProperties

• Properties are the values associated with an object.

• In the following example we are using the length property of the String object to return the number of characters in a string:<script type="text/javascript">var txt="Hello World!";document.write(txt.length);</script>

• The output of the code above will be:12

Page 169: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

169 /294

JavaScript Objects IntroductionMethods

• Methods are the actions that can be performed on objects.

• In the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters:<script type="text/javascript">var str="Hello world!";document.write(str.toUpperCase());</script>

• The output of the code above will be:HELLO WORLD!

Page 170: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

170 /294

JavaScript String Object

• The String object is used to manipulate a stored piece of text.

• Examples of use:• The following example uses the length property of

the String object to find the length of a string:var txt="Hello world!";document.write(txt.length);

• The code above will result in the following output:12

Page 171: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

171 /294

JavaScript String ObjectUseful Properties - Constructor

• Constructor : The constructor property returns the function that created the String object's prototype.

• Syntaxstring.constructor

• Examplevar txt = "Hello World!";document.write(txt.constructor);

• The output of the code above will be:function String() { [native code] }

Page 172: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

172 /294

JavaScript String ObjectUseful Properties - Prototype

• Prototype : The prototype property allows you to add properties and methods to an object.

• Note: Prototype is a global property which is available with almost all JavaScript objects.

• Syntaxobject.prototype.name=value

Page 173: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

173 /294

JavaScript String ObjectUseful Properties - Prototype

function employee(name,jobtitle,born){this.name=name;this.jobtitle=jobtitle;this.born=born;}

var fred=new employee("Fred Flintstone","Caveman",1970);employee.prototype.salary=null;fred.salary=20000;

document.write(fred.salary);

Page 174: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

175 /294

JavaScript String ObjectUseful Methods – charAt()

• charAt(index) : returns the character at the specified index in a string.

• The index of the first character is 0, the second character is 1, and so on.

• Syntaxstring.charAt(index)

• Parameter Values–Index : Required. An integer representing the index

of the character you want to return

• Return Value–String : The character at the specified index

Page 175: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

176 /294

JavaScript String ObjectUseful Methods – charCodeAt()

• charCodeAt(index) : returns the Unicode of the character at the specified index in a string.

• The index of the first character is 0, the second character is 1, and so on.

• Syntaxstring.charCodeAt(index)

• Parameter Values–Index : Required. An integer representing the index

of the character you want to return

• Return Value–Number : The unicode of the character at the

specified index

Page 176: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

177 /294

JavaScript String ObjectUseful Methods – concat()

• concat(s1,s2,…) : is used to join two or more strings.

• This method does not change the existing strings, but returns a new string containing the text of the joined strings.

• Syntaxstring.concat(string1, string2, ..., stringX)

• Parameter Values–string1, string2, ..., stringX : Required. The strings to

be joined.

• Return Value–String : A new string, containg the text of the

combined strings .

Page 177: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

178 /294

JavaScript String ObjectUseful Methods – fromCharCode()

• fromCharCode(n1,n2,…) : converts Unicode values into characters.

• This method does not change the existing strings, but returns a new string containing the text of the joined strings.

• SyntaxString.fromCharCode(n1, n2, ..., nX)

• Parameter Values–n1, n2, ..., nX : Required. One or more Unicode

values to be converted• Return Value

–String : The character(s) representing the specified unicode number(s)

Page 178: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

179 /294

JavaScript String ObjectUseful Methods – indexOf()

• indexOf(string) : returns the position of the first occurrence of a specified value in a string.

• This method returns -1 if the value to search for never occurs.

• Note: The indexOf() method is case sensitive.• Syntaxstring.indexOf(searchvalue,start)

• Parameter Values– searchvalue : Required. The string to search for– start : Optional. Default 0. At which postition to start the search

• Return Value–Number : The position where the specified searchvalue occurs

for the first time, or -1 if it never occurs.

Page 179: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

180 /294

JavaScript String ObjectUseful Methods – lastIndexOf()• lastIndexOf(string) : returns the position of the last

occurrence of a specified value in a string.• Note: The string is searched from the end to the beginning,

but returns the index starting at the beginning, at postion 0.• This method returns -1 if the value to search for never

occurs.• Syntaxstring.indexOf(searchvalue,start)

• Parameter Values– searchvalue : Required. The string to search for– start : Optional. The position where to start the search. If

omitted, the default value is the length of the string .• Return Value

–Number : The position where the specified searchvalue occurs for the last time, or -1 if it never occurs .

Page 180: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

181 /294

JavaScript String ObjectUseful Methods – replace()

• replace(s1,s2) : searches a string for a specified value, or a regular  expression, and returns a new string where the specified values are replaced.

• This method does not change the original string.• Syntaxstring.replace(searchvalue,newvalue)

• Parameter Values– searchvalue : Required. The value, or regular expression,

that will be replaced by the new value. – newvalue : Required. The value to replace the

searchvalue with.• Return Value

–String : A new string where the specified value(s) has been replaced by the new value.

Page 181: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

182 /294

JavaScript String ObjectUseful Methods – search()

• search(string) : searches a string for a specified value, or regular  expression, and returns the position of the match. This method returns -1 if no match is found.

• Syntaxstring.search(searchvalue)

• Parameter Values– searchvalue : Required. The value, or regular expression,

to search for.• Return Value

–Number : The position of the first occurance of the specified searchvalue

Page 182: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

183 /294

JavaScript String ObjectUseful Methods – slice()

• Slice(start,end) : extract parts of a string and returns the extracted parts in a new string.

• Use the start and end parameters to specify the part of the string you want to extract.

• The first character has the position 0, the second has position 1, and so on.

• Tip: Use a negative number to select from the end of the string.

• Syntaxstring.slice(start,end)

Page 183: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

184 /294

JavaScript String ObjectUseful Methods – slice()

• Parameter Values– Start  : Required. The position where to begin the

extraction. First character is at position 0.– End  : Optional. The position (up to, but not including)

where to end the extraction, If omitted, slice() selects all characters from the start-position to the end of the string

• Return Value–String : The extracted part of the string

Page 184: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

185 /294

JavaScript String ObjectUseful Methods – split()

• Split(seperator,limit) : is used to split a string into an array of substrings, and returns the new array.

• Tip: If an empty string ("") is used as the separator, the string is split between each character.

• Note: The split() method does not change the original string.

• Syntaxstring.split(separator,limit)

Page 185: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

186 /294

JavaScript String ObjectUseful Methods – split()

• Parameter Values– separatorOptional. Specifies the character to

use for splitting the string. If omitted, the entire string will be returned (an array with only one item).

– Limit  : Optional. An integer that specifies the number of splits, items after the split limit will not be included in the array

• Return Value–Array : An array containing the spitted values

Page 186: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

187 /294

JavaScript String ObjectUseful Methods – substr()

• substr(start,length) : extracts parts of a string, beginning at the character at the specified posistion, and returns the specified number of characters.

• Tip: To extract characters from the end of the string, use a negative start number (This does not work in IE 8 and earlier).

• Note: The substr() method does not change the original string.

• Syntaxstring.substr(start,length)

Page 187: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

188 /294

JavaScript String ObjectUseful Methods – substr()

• Parameter Values– startRequired. The postition where to start the

extraction. First character is at index 0.– Length : Optional. The number of characters to

extract. If omitted, it extracts the rest of the string.

• Return Value–String : A new string containing the extracted

part of the text.

Page 188: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

189 /294

JavaScript String ObjectUseful Methods – substring()

• substring(from,to) : extracts the characters from a string, between two specified indices, and returns the new sub string.

• This method extracts the characters in a string between "from" and "to", not including "to" itself.

• Syntax string.substring(from, to)

Page 189: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

190 /294

JavaScript String ObjectUseful Methods – substring()

• Parameter Values– From : Required. The index where to start the

extraction. First character is at index 0.– To : Optional. The index where to stop the

extraction. If omitted, it extracts the rest of the string

• Return Value–String : The substring between from position

and to position.

Page 190: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

191 /294

JavaScript String ObjectUseful Methods – other…

• The toLowerCase() method converts a string to lowercase letters.

• The toUpperCase() method converts a string to uppercase letters.

• The valueOf() method returns the primitive value of a String object.

• Note: This method is usually called automatically by JavaScript behind the scenes, and not explicitly in code.

Page 191: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

192 /294

JavaScript String ObjectString HTML Wrapper Methods

• The anchor() method is used to create an HTML anchor.

• This method returns the string embedded in the <a> tag, like this:<a name="anchorname">string</a>

• Syntaxstring.anchor(name)

Page 192: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

193 /294

JavaScript String ObjectString HTML Wrapper Methods

• The big() method is used to display a string in a big font.

• This method returns the string embedded in the <big> tag, like this:<big>string</big>

• Syntaxstring.big()

Page 193: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

194 /294

JavaScript String ObjectString HTML Wrapper Methods

• The bold() method is used to display a string in bold.

• This method returns the string embedded in the <b> tag, like this:<b>string</b>

• Syntaxstring.bold()

Page 194: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

195 /294

JavaScript String ObjectString HTML Wrapper Methods

• The fixed() method is used to display a string as teletype text.

• This method returns the string embedded in the <tt> tag, like this:<tt>string</tt>

• Syntaxstring.fixed()

Page 195: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

196 /294

JavaScript String ObjectString HTML Wrapper Methods

• The fontcolor() method is used to display a string in a specified color.

• This method returns the string embedded in the <font> tag, like this:<font color="colorvalue">string</font>

• Syntaxstring.fontcolor(color)

Page 196: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

197 /294

JavaScript String ObjectString HTML Wrapper Methods

• The fontsize() method is used to display a string in a specified size.

• This method returns the string embedded in the <font> tag, like this:<font size="size">string</font>

• Syntaxstring.fontsize(size)

Page 197: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

198 /294

JavaScript String ObjectString HTML Wrapper Methods

• The italics() method is used to display a string in italic.

• This method returns the string embedded in the <i> tag, like this:<i>string</i>

• Syntaxstring.italics()

Page 198: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

199 /294

JavaScript String ObjectString HTML Wrapper Methods

• The link() method is used to display a string as a hyperlink.

• This method returns the string embedded in the <a> tag, like this:<a href="url">string</a>

• Syntaxstring.link(url)

Page 199: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

200 /294

JavaScript String ObjectString HTML Wrapper Methods

• The small() method is used to display a string in a small font.

• This method returns the string embedded in the <small> tag, like this:<small>string</small>

• Syntaxstring.small()

Page 200: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

201 /294

JavaScript String ObjectString HTML Wrapper Methods

• The strike() method is used to display a string that is struck out.

• This method returns the string embedded in the <strike> tag, like this:<strike>string</strike>

• Syntaxstring.strike()

Page 201: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

202 /294

JavaScript String ObjectString HTML Wrapper Methods

• The sub() method is used to display a string as subscript text.

• This method returns the string embedded in the <sub> tag, like this:<sub>string</sub>

• Syntaxstring.sub()

Page 202: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

203 /294

JavaScript String ObjectString HTML Wrapper Methods

• The sup() method is used to display a string as superscript text.

• This method returns the string embedded in the <sup> tag, like this:<sup>string</sup>

• Syntaxstring.sup()

Page 203: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

204 /294

JavaScript Date ObjectCreate a Date Object

• The Date object is used to work with dates and times.

• Date objects are created with the Date() constructor.

• There are four ways of initiating a date:new Date() // current date and timenew Date(milliseconds) //milliseconds since 1970/01/01new Date(dateString)new Date(year, month, day, hours, minutes, seconds,

milliseconds)

Page 204: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

205 /294

JavaScript Date ObjectCreate a Date Object

• Most parameters above are optional. Not specifying, causes 0 to be passed in.

• Once a Date object is created, a number of methods allow you to operate on it. Most methods allow you to get and set the year, month, day, hour, minute, second, and milliseconds of the object, using either local time or UTC (universal, or GMT) time.

• All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC) with a day containing 86,400,000 milliseconds.

Page 205: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

206 /294

JavaScript Date ObjectSet Dates

• We can easily manipulate the date by using the methods available for the Date object.

• In the example below we set a Date object to a specific date (14th January 2010):var myDate=new Date();myDate.setFullYear(2010,0,14);

• And in the following example we set a Date object to be 5 days into the future:var myDate=new Date();myDate.setDate(myDate.getDate()+5);

• Note: If adding five days to a date shifts the month or year, the changes are handled automatically by the Date object itself!

Page 206: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

207 /294

JavaScript Date ObjectCompare Two Dates

• The Date object is also used to compare two dates.• The following example compares today's date with the 14th

January 2100:var x=new Date();x.setFullYear(2100,0,14);var today = new Date();

if (x>today) { alert("Today is before 14th January 2100"); }else { alert("Today is after 14th January 2100"); }

Page 207: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

208 /294

JavaScript Date ObjectProperties

• Constructor : such as string• Prototype :

–The prototype constructor allows you to add new properties and methods to the Date() object.

–When constructing a property, ALL date objects will be given the property, and it's value, as default.

–When constructing a method, ALL date objects will have this method available.

–Note: Date.prototype does not refer to a single date object, but to the Date() object itself.

–Note: Prototype is a global object constructor which is available for all JavaScript objects.

• SyntaxDate.prototype.name=value

Page 208: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

209 /294

JavaScript Date ObjectProperties - prototype

• Example• Make a new date method that gives the date object a

month-name property called myProp:Date.prototype.myMet=function(){if (this.getMonth()==0){this.myProp="January"};if (this.getMonth()==1){this.myProp="February"};if (this.getMonth()==2){this.myProp="March"};}

• Make a Date object, then call the myMet method:var d = new Date();d.myMet();var monthname = d.myProp;

• The result of monthname will be:March

Page 209: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

210 /294

JavaScript Date ObjectMethods- getDate()

• getDate() : returns the day of the month (from 1 to 31) for the specified date.

• SyntaxDate.getDate()

• Return Value–Number : A number from 1 to 31, representing the

day of the month• Example• Return the day of the month from a specific date:

var d = new Date("July 21, 1983 01:15:00");var n = d.getDate();

• The output of the code above will be:21

Page 210: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

211 /294

JavaScript Date ObjectMethods- getDay()

• getDay() : returns the day of the week (from 0 to 6) for the specified date.

• Note: Sunday is 0, Monday is 1, and so on.• SyntaxDate.getDay()

• Return Value–Number : A Number, from 0 to 6, representing the

day of the week.

Page 211: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

212 /294

JavaScript Date ObjectMethods- getDay()

• Example• Return the name of the weekday (not just a number):

var d=new Date();var weekday=new Array(7);weekday[0]="Sunday";weekday[1]="Monday";weekday[2]="Tuesday";weekday[3]="Wednesday";weekday[4]="Thursday";weekday[5]="Friday";weekday[6]="Saturday";

var n = weekday[d.getDay()]; • The result of n will be:

Sunday

Page 212: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

213 /294

JavaScript Date ObjectMethods- getFullYear()

• getFullYear() : returns the year (four digits) of the specified date.

• SyntaxDate.getFullYear()

• Return Value–Number : Four digits, representing the year.

• Example• Return the year of a specific date:

var d = new Date("July 21, 1983 01:15:00");var n = d.getFullYear();

• The result of n will be:1983

Page 213: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

214 /294

JavaScript Date ObjectMethods- getMilliseconds()

• getMilliseconds() : returns the milliseconds (from 0 to 999) of the specified date and time.

• SyntaxDate.getMilliseconds()

• Return Value–Number : A Number, from 0 to 999, representing

milliseconds.• Example• Return the milliseconds from a specific date and time:

var d = new Date("July 21, 1983 01:15:00:526");var n = d.getMilliseconds();

• The result of n will be:526

Page 214: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

215 /294

JavaScript Date ObjectMethods- getMinutes()

• getMinutes() : returns the minutes (from 0 to 59) of the specified date and time.

• SyntaxDate.getMinutes()

• Return Value–Number : A Number, from 0 to 59, representing minutes.

• Example• Return the minutes from a specific date and time:

var d = new Date("July 21, 1983 01:15:00");var n = d.getMinutes();

• The result of n will be:15

Page 215: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

216 /294

JavaScript Date ObjectMethods- getMonth()

• getMonth() : returns the month (from 0 to 11) for the specified date, according to local time.

• Note: January is 0, February is 1, and so on. • SyntaxDate.getMonth()

• Return Value–Number : A Number, from 0 to 11, representing the month.

Page 216: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

217 /294

JavaScript Date ObjectMethods- getMonth()

• Return the name of the month (not just a number):

var d=new Date();var month=new Array();month[0]="January";month[1]="February";month[2]="March";month[3]="April";month[4]="May";month[5]="June";month[6]="July";

month[7]="August";month[8]="September";month[9]="October";month[10]="November";month[11]="December";

var n = month[d.getMonth()];

Output : July

Page 217: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

218 /294

JavaScript Date ObjectMethods- getSeconds()

• getSeconds() : returns the seconds (from 0 to 59) of the specified date and time.

• SyntaxDate.getSeconds()

• Return Value–Number : A Number, from 0 to 59, representing the

seconds.• Example• Return the seconds, according to local time:

var d = new Date();var n = d.getSeconds();

• The result of n could be:31

Page 218: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

219 /294

JavaScript Date ObjectMethods- getTime()

• getTime() : returns the number of milliseconds between midnight of January 1, 1970 and the specified date.

• SyntaxDate.getTime()

• Return Value–Number : Milliseconds since midnight January 1, 1970 .

• Example• Calculate the number of years since 1970/01/01:

var minutes=1000*60;var hours=minutes*60;var days=hours*24;var years=days*365;var d=new Date();var t=d.getTime();var y=Math.round(t/years);

The result of y will be:43

Page 219: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

220 /294

JavaScript Date ObjectMethods- getTimezoneOffset()

• getTimezoneOffset() : returns the time difference between UTC time and local time, in minutes.

• For example, If your time zone is GMT+2, -120 will be returned.

• Note: The returned value is not a constant, because of the practice of using Daylight Saving Time.

• Tip: The Universal Coordinated Time (UTC) is the time set by the World Time Standard.

• Note: UTC time is the same as GMT time.• SyntaxDate.getTimezoneOffset()

• Return Value–Number : The time difference between UTC and Local Time,

in minutes.

Page 220: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

221 /294

JavaScript Date ObjectMethods- getTimezoneOffset()

• Example• Return the timezone difference between UTC and

Local Time:var d = new Date()var n = d.getTimezoneOffset();

• The result n will be:-210

Page 221: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

222 /294

JavaScript Date ObjectMethods- parse()

• parse() : parses a date string and returns the number of milliseconds between the date string and midnight of January 1, 1970.

• SyntaxDate.parse(datestring)

• Parameter Values• datestring : Required. A string representing a date.• Return Value–Number : Milliseconds between the specified date-time

and midnight January 1, 1970.• var d = Date.parse("March 21, 2012"); => 1332275400000

Page 222: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

223 /294

JavaScript Date ObjectMethods- setFullYear()

• setFullYear() : sets the year (four digits) of the date object.• This method can also be used to set the month and day of

month.• Syntax : Date.setFullYear(year,month,day)• Parameter Values

–Year : Required. A four-digit value representing the year, negative values are allowed.–month : Optional. An integer representing the month Expected values are 0-11, but other values are allowed:

•-1 will result in the last month of the previous year.•12 will result in the first month of the next year.•13 will result in the second month of the next year.

Page 223: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

224 /294

JavaScript Date ObjectMethods- setFullYear()

–day : Optional. An integer representing the day of month Expected values are 1-31, but other values are allowed:

•0 will result in the last hour of the previous month•-1 will result in the hour before the last hour of the

previous monthIf the month has 31 days:

•32 will result in the first day of the next monthIf the month has 30 days:

•32 will result in the second day of the next month

• Return Value–Number : Milliseconds between the date object and

midnight January 1 1970.

Page 224: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

225 /294

JavaScript Date ObjectMethods- setHours()

• setHours() : sets the hour of a date object.• This method can also be used to set the minutes, seconds

and milliseconds.• Syntax : Date.setHours(hour,min,sec,millisec)• Parameter Values

–Hour : Required. An integer representing the hour. Expected values are 0-23, but other values are allowed:

•-1 will result in the last hour of the previous day•24 will result in the first hour of the next day

–min Optional. An integer representing the minutes. Expected values are 0-59, but other values are allowed:

•-1 will result in the last minute of the previous hour•60 will result in the first minute of the next hour

Page 225: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

226 /294

JavaScript Date ObjectMethods- setHours()

–Sec : Optional. An integer representing the seconds Expected values are 0-59, but other values are allowed:

•-1 will result in the last second of the previous minute•60 will result in the first second of the next minute

–millisec : Optional. An integer representing the milliseconds Expected values are 0-999, but other values are allowed:

•-1 will result in the last millisecond of the previous second

•1000 will result in the first millisecond of the next second

• Return Value–Number : Milliseconds between the date

object and midnight January 1 1970

Page 226: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

227 /294

JavaScript Date ObjectMethods- setMilliseconds ()

• setMilliseconds() : sets the milliseconds of a date object.• Syntax : Date.setMilliseconds(millisec)• Parameter Values

–millisec : Required. An integer representing the milliseconds Expected values are 0-999, but other values are allowed:

•-1 will result in the last millisecond of the previous second

•1000 will result in the first millisecond of the next second

•1001 will result in the second millisecond of the next second

• Return Value–Number : Milliseconds between the date object and

midnight January 1 1970

Page 227: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

228 /294

JavaScript Date ObjectMethods- setMinutes ()

• setMinutes() : sets the minutes of a date object.• This method can also be used to set the seconds and

milliseconds.• Syntax : Date.setMinutes(min,sec,millisec)• Parameter Values

–Min  : Required. An integer representing the minutes. Expected values are 0-59, but other values are allowed:

•-1 will result in the last minute of the previous hour•60 will result in the first minute of the next hour

–Sec : Optional. An integer representing the seconds Expected values are 0-59, but other values are allowed:

•-1 will result in the last second of the previous minute•60 will result in the first second of the next minute

Page 228: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

229 /294

JavaScript Date ObjectMethods- setMinutes ()

–Millisec  : Optional. An integer representing the milliseconds Expected values are 0-999, but other values are allowed:

•-1 will result in the last millisecond of the previous second

•1000 will result in the first millisecond of the next second

• Return Value–Number : Milliseconds between the date object and

midnight January 1 1970

Page 229: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

230 /294

JavaScript Date ObjectMethods- setMonth()

• setMonth() : sets the month of a date object.• Note: January is 0, February is 1, and so on.• This method can also be used to set the day of the month.• Syntax : Date.setMonth(month,day)• Parameter Values

–Month  : Required. An integer representing the month Expected values are 0-11, but other values are allowed:

•-1 will result in the last month of the previous year•12 will result in the first month of the next year•13 will result in the second month of the next year

Page 230: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

231 /294

JavaScript Date ObjectMethods- setMonth()

–day Optional. An integer representing the day of month Expected values are 1-31, but other values are allowed:

•0 will result in the last hour of the previous month•-1 will result in the hour before the last hour of the

previous monthIf the month has 31 days:

•32 will result in the first day of the next monthIf the month has 30 days:

•32 will result in the second day of the next month

• Return Value–Number : Milliseconds between the date object and

midnight January 1 1970.

Page 231: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

232 /294

JavaScript Date ObjectMethods- setSeconds()

• setSeconds() sets the seconds of a date object.• This method can also be used to set the milliseconds.• Syntax : Date.setSeconds(sec,millisec)• Parameter Values

–Sec : Required. An integer representing the secondsExpected values are 0-59, but other values are allowed:

•-1 will result in the last second of the previous minute

•60 will result in the first second of the next minute

Page 232: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

233 /294

JavaScript Date ObjectMethods- setSeconds()

–Millisec  :  Optional. An integer representing the millisecondsExpected values are 0-999, but other values are allowed:

•-1 will result in the last millisecond of the previous second

•1000 will result in the first millisecond of the next second

• Return Value–Number : Milliseconds between the date object and

midnight January 1 1970

Page 233: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

234 /294

JavaScript Date ObjectMethods- setTime()

• setTime() sets a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970.

• Syntax : Date.setTime(millisec)• Parameter Values

–millisec : Required. The number of milliseconds to be added to, or subtracted from, midnight January 1, 1970

• Return Value

–Number : Milliseconds between the date object and midnight January 1 1970

Page 234: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

235 /294

JavaScript Date ObjectMethods- setTime()

• Example• Subtract 1332403882588 milliseconds from January 1, 1970,

and display the new date and time:var d = new Date();d.setTime(-1332403882588);

• The result of d will be:Wed Oct 12 1927 19:18:37 GMT+0330 (Iran Standard Time)

Page 235: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

236 /294

JavaScript Date ObjectMethods- toDateString()

• toDateString() converts the date (not the time) of a Date object into a readable string.

• Syntax : Date.toDateString(millisec)• Return Value

–String : The date as a string.

Page 236: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

237 /294

JavaScript Date ObjectMethods- toString()

• toString() converts a Date object to a string.• Note: This method is automatically called by

JavaScript whenever a Date object needs to be displayed as a string.

• Syntax : Date.toString()• Return Value

–String : The date and time as a string.

Page 237: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

238 /294

JavaScript Date ObjectMethods- toString()

• Example• Convert a Date object to a string:

var d=new Date();var n=d.toString();

• The result of n will be:Mon Aug 06 2012 01:04:15 GMT+0430 (Iran Daylight Time)

Page 238: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

239 /294

JavaScript Array ObjectWhat is an Array?

• An array is a special variable, which can hold more than one value, at a time.

• If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:var car1="Saab";var car2="Volvo";var car3="BMW";

• However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

Page 239: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

240 /294

JavaScript Array ObjectWhat is an Array?

• The best solution here is to use an array!• An array can hold all your variable values under a

single name. And you can access the values by referring to the array name.

• Each element in the array has its own ID so that it can be easily accessed.

Page 240: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

241 /294

JavaScript Array ObjectCreate an Array?

• An array can be defined in three ways. • The following code creates an Array object called

myCars:• 1:

var myCars=new Array(); // regular array (add an optional integermyCars[0]="Saab"; // argument to control array's size)myCars[1]="Volvo";myCars[2]="BMW";

Page 241: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

242 /294

JavaScript Array ObjectCreate an Array?

• 2:var myCars=new Array("Saab","Volvo","BMW"); // condensed array

• 3:var myCars=["Saab","Volvo","BMW"]; // literal array

• Note: If you specify numbers or true/false values inside the array then the variable type will be Number or Boolean, instead of String.

Page 242: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

243 /294

JavaScript Array ObjectAccess an Array?

• You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.

• The following code line:document.write(myCars[0]);

• will result in the following output:Saab

Page 243: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

244 /294

JavaScript Array ObjectModify values in an Array?

• To modify a value in an existing array, just add a new value to the array with a specified index number:myCars[0]="Opel";

• Now, the following code line:document.write(myCars[0]);

• will result in the following output:Opel

Page 244: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

245 /294

JavaScript Array ObjectProperties- constructor , list , prototype

• The length property sets or returns the number of elements in an array.

• Syntax–Set the length of an array:

array.length=number–Return the length of an array:

array.length

Page 245: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

246 /294

JavaScript Array ObjectMethods – concat()

• concat() is used to join two or more arrays.• This method does not change the existing arrays,

but returns a new array, containing the values of the joined arrays.

• Syntax–array1.concat(array2,array3,...,arrayX)

• Parameter Values–array2, array3, ..., arrayX : Required. The arrays to be joined

• Return Value–Array : objectThe joined array

Page 246: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

247 /294

JavaScript Array ObjectMethods – indexOf()

• indexOf() searches the array for the specified item, and returns it's position.

• The search will start at the specified position, or at the beginning if no start position is specified, and end the search at the end of the array.

• Returns -1 if the item is not found.• If the item is present more than once, the indexOf

method returns the position of the first occurence.• Note: The first item has position 0, the second

item has position 1, and so on.

Page 247: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

248 /294

JavaScript Array ObjectMethods – indexOf()

• Syntax–array.indexOf(item,start)

• Parameter Values–Item : Required. The item to search for.–Start  :  Optional. Where to start the search.

Negative values will start at the given position counting from the end, and search to the end.

• Return Value–Number : The position of the specified item,

otherwise -1

Page 248: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

249 /294

JavaScript Array ObjectMethods – indexOf()

• Example• Search an array for the item "Apple",

starting the search at position 4:var fruits=["Banana","Orange","Apple","Mango","Banana","Orange","Apple"];var a = fruits.indexOf("Apple",4);

• The result of a will be:6

Page 249: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

250 /294

JavaScript Array ObjectMethods – join()

• join() joins the elements of an array into a string, and returns the string.

• The elements will be separated by a specified separator. The default separator is comma (,).

• Syntaxarray.join(separator)

• Parameter Values–separator : Optional. The separator to be used. If

omitted, the elements are separated with a comma

Page 250: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

251 /294

JavaScript Array ObjectMethods – join()

• Return Value–String : The array values, separated by the

specified separator .

• Example• Try using a different separator:

var fruits = ["Banana", "Orange", "Apple", "Mango"];var energy = fruits.join(" and ");

• The result of energy will be:Banana and Orange and Apple and Mango

Page 251: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

252 /294

JavaScript Array ObjectMethods – lastIndexOf()

• lastIndexOf() searches the array for the specified item, and returns it's position.

• The search will start at the specified position, or at the end if no start position is specified, and end the search at the beginning of the array.

• Returns -1 if the item is not found.• If the item to search for is present more

than once, the lastIndexOf method returns the position of the last occurence.

Page 252: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

253 /294

JavaScript Array ObjectMethods – lastIndexOf()

• Syntaxarray.lastIndexOf(item,start)

• Parameter Values–item : Required. The item to searc for.–start : Optional. Where to start the search.

Negative values will start at the given position counting from the end, and search to the beginning

• Return Value–Number : The osition of the specified item,

otherwise -1

Page 253: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

254 /294

JavaScript Array ObjectMethods – lastIndexOf()

• Example• Search an array for the item "Apple",

starting the search at position 4:var fruits=["Banana","Orange","Apple","Mango","Banana","Orange","Apple"];var a = fruits.lastIndexOf("Apple",4);

• The result of a will be:2

Page 254: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

255 /294

JavaScript Array ObjectMethods – pop()

• pop() removes the last element of an array, and returns that element.

• Note: This method changes the length of an array.

• Tip: To remove the first element of an array, use the shift() method.

• Syntax–array.pop()

Page 255: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

256 /294

JavaScript Array ObjectMethods – pop()

• Return Value–Any type* : The removed array item.

*An array item can be a string, a number, an array, a boolean, or any other object types that are allowed in an array.

var fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.pop();

• The result of fruit will be:Banana,Orange,Apple

Page 256: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

257 /294

JavaScript Array ObjectMethods – push()

• The push() method adds new items to the end of an array, and returns the new length.

• Note: The new item(s) will be added at the end of the array.

• Note: This method changes the length of the array.

• Tip: To add items at the beginning of an array, use the unshift() method.

Page 257: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

258 /294

JavaScript Array ObjectMethods – push()

• Syntax–array.push(item1, item2, ..., itemX)

• Parameter Values–item1, item2, ..., itemX : Required. The

item(s) to add to the array.

• Return Value–Number : The new length of the array

Page 258: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

259 /294

JavaScript Array ObjectMethods – push()

• Example• Add more than one item:

var fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.push("Kiwi","Lemon","Pineapple")

• The output of the code above will be:–Banana,Orange,Apple,Mango,Kiwi,Lemon,

Pineapple

Page 259: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

260 /294

JavaScript Array ObjectMethods – reverse()• The reverse() method reverses the order of

the elements in an array.• Syntax

–array.reverse()

• Return Value–Array : The array after it has been reversed

• Example• Reverse the order of the elements in an array:

var fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.reverse();

• The result of fruits will be:–Mango,Apple,Orange,Banana

Page 260: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

261 /294

JavaScript Array ObjectMethods – shift()

• The shift() method removes the first item of an array, and returns that item.

• Note: This method changes the length of an array!• Tip: To remove the last item of an array, use the

pop() method.• Syntax

–array.shift()

• Return Value–Any type* : The removed array item

• *An array item can be a string, a number, an array, a boolean, or any other object types that are allowed in an array.

Page 261: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

262 /294

JavaScript Array ObjectMethods – shift()

• Example• Remove the first item of an array:

var fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.shift()

• The result of fruits will be:Orange,Apple,Mango

Page 262: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

263 /294

JavaScript Array ObjectMethods – slice()

• The slice() method returns the selected elements in an array, as a new array object.

• The slice() method selects the elements starting at the given start argument, and ends at, but  does  not  include, the given end argument.

• Note: The original array will not be changed.

Page 263: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

264 /294

JavaScript Array ObjectMethods – slice()

• Syntax–array.slice(start, end)

• Parameter Values–Start  : Required. An integer that specifies

where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array.–End  :  Optional. An integer that specifies

where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array

Page 264: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

265 /294

JavaScript Array ObjectMethods – slice()

• Return Value–Array : A new array, containing the

selected elements.• Example• Select elements using negative values:

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];var myBest = fruits.slice(-3,-1);

• The result of myBest will be:Lemon,Apple

Page 265: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

266 /294

JavaScript Array ObjectMethods – sort()

• The sort() method sorts the items of an array.• The sort order can be either alphabetic or numeric,

and either ascending or descending.• Default sort order is alphabetic and ascending.• Note: When numbers are sorted alphabetically,

"40" comes before "5".• To perform a numeric sort, you must pass a

function as an argument when calling the sort method.

Page 266: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

267 /294

JavaScript Array ObjectMethods – sort()• The function specifies whether the numbers

should be sorted ascending or descending.• It can be difficult to understand how this function

works, but see the examples at the bottom of this page.

• Note: This method changes the original array.• Syntax

–array.sort(sortfunction)

• Parameter Values–Sortfunction : Optional. A function that defines the

sort order

• Return Value–Array : The Array object, with the items sorted

Page 267: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

268 /294

JavaScript Array ObjectMethods – sort()

• Example• Sort numbers (numerically and ascending):

var points = [40,100,1,5,25,10];points.sort(function(a,b){return a-b});

• The result of points will be:1,5,10,25,40,100

Page 268: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

269 /294

JavaScript Array ObjectMethods – sort()

• Example• Sort numbers (numerically and descending):

var points = [40,100,1,5,25,10];points.sort(function(a,b){return b-a});

• The result of points will be:100,40,25,10,5,1

Page 269: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

270 /294

JavaScript Array ObjectMethods – splice()

• The splice() method adds/removes items to/from an array, and returns the removed item(s).

• Note: This method changes the original array.• Syntax

–array.splice(index,howmany,item1,.....,itemX)

• Parameter Values–Index  : Required. An integer that specifies at what

position to add/remove items, Use negative values to specify the position from the end of the array.

–Howmany  :  Required. The number of items to be removed. If set to 0, no items will be removed.

–item1, ..., itemX  : Optional. The new item(s) to be added to the array

Page 270: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

271 /294

JavaScript Array ObjectMethods – splice()

• Return Value–Array : A new array containing the removed items,

if any.

• Example• At position 2, add the new items, and remove 1

item:var fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.splice(2,1,"Lemon","Kiwi");

• The result of fruits will be:Banana,Orange,Lemon,Kiwi,Mango

Page 271: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

272 /294

JavaScript Array ObjectMethods – toString()

• The toString() method converts an array into a String and returns the result.

• Note: The returned string will separate the elements in the array with commas.

• Syntax–array.toString()

• Return Value–String : All the values of the array,

separated by a comma

Page 272: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

273 /294

JavaScript Array ObjectMethods – unshift()

• The unshift() method adds new items to the beginning of an array, and returns the new length.

• Note: This method changes the length of an array.

• Tip: To add new items at the end of an array, use the push() method.

• Note: The unshift() method returns undefined in Internet Explorer 8 and earlier.

Page 273: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

274 /294

JavaScript Array ObjectMethods – unshift()

• Syntax–array.unshift(item1,item2, ..., itemX)

• Parameter Values–item1,item2, ..., itemX  :  Required. The

item(s) to add to the beginning of the array

• Return Value–Number : The new length of the array

Page 274: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

275 /294

JavaScript Array ObjectMethods – valueOf()

• The valueOf() method returns the array.• This method is the default method of the

array object. Array.valueOf() will return the same as Array

• Note: This method will not change the original array.

• Syntax–array.valueOf()

• Return Value–Array : The valueOf() method returns itself

Page 275: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

276 /294

JavaScript Boolean ObjectCreate a Boolean Object

• The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false).

• The Boolean object represents two values: "true" or "false".

• The following code creates a Boolean object called myBoolean:

• var myBoolean=new Boolean();

Page 276: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

277 /294

JavaScript Boolean ObjectCreate a Boolean Object

• If the Boolean object has no initial value, or if the passed value is one of the following:

• 0 , -0 , null , “” , false , undefined , NaN• the object is set to false. For any other

value it is set to true (even with the string "false")!

Page 277: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

278 /294

JavaScript Boolean ObjectMethods – toString()

• The toString() method converts a Boolean value to a string, and returns the result.

• Note: This method is called by JavaScript automatically whenever a Boolean object is used in a situation requiring a string.

• Syntax–boolean.toString()

• Return Value–String : Either "true" or "false"

Page 278: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

279 /294

JavaScript Boolean ObjectMethods – valueOf()

• The valueOf() method returns the primitive value of a Boolean object.

• Syntax–boolean.valueOf()

• Return Value–String : Either "true" or "false"

Page 279: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

280 /294

JavaScript Math Object

• The Math object allows you to perform mathematical tasks.

• The Math object includes several mathematical constants and methods.

• Syntax for using properties/methods of Math:var x=Math.PI;var y=Math.sqrt(16);

• Note: Math is not a constructor. All properties and methods of Math can be called by using Math as an object without creating it.

Page 280: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

281 /294

JavaScript Math Object Mathematical Constants

• JavaScript provides eight mathematical constants that can be accessed from the Math object. These are: E, PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log of E.

• You may reference these constants from your JavaScript like this:

• Math.E , Math.PI , Math.SQRT2 , Math.SQRT1_2 , Math.LN2 , Math.LN10 , Math.LOG2E , Math.LOG10E

Page 281: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

282 /294

JavaScript Math Object Mathematical Methods

• In addition to the mathematical constants that can be accessed from the Math object there are also several methods available.

• The following example uses the round() method of the Math object to round a number to the nearest integer:document.write(Math.round(4.7));

• The code above will result in the following output:5

Page 282: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

283 /294

JavaScript Math Object Mathematical Methods

• The following example uses the random() method of the Math object to return a random number between 0 and 1:document.write(Math.random());

• The code above can result in the following output:0.7175638044285627

• The following example uses the floor() and random() methods of the Math object to return a random number between 0 and 10:document.write(Math.floor(Math.random()*11));

• The code above can result in the following output:7

Page 283: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

284 /294

JavaScript Math Object Mathematical Properties

Page 284: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

285 /294

JavaScript Math Object Mathematical Methods List

Page 285: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

286 /294

JavaScript RegExp ObjectWhat is RegExp ?

• A regular expression is an object that describes a pattern of characters.

• When you search in a text, you can use a pattern to describe what you are searching for.

• A simple pattern can be one single character.• A more complicated pattern can consist of more

characters, and can be used for parsing, format checking, substitution and more.

• Regular expressions are used to perform powerful pattern-matching and "search-and-replace" functions on text.

Page 286: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

287 /294

JavaScript RegExp ObjectWhat is RegExp ?

• A regular expression is an object that describes a pattern of characters.

• When you search in a text, you can use a pattern to describe what you are searching for.

• A simple pattern can be one single character.• A more complicated pattern can consist of more

characters, and can be used for parsing, format checking, substitution and more.

• Regular expressions are used to perform powerful pattern-matching and "search-and-replace" functions on text.

Page 287: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

288 /294

JavaScript RegExp ObjectWhat is RegExp ?

• Syntaxvar patt=new RegExp(pattern,modifiers);

or more simply:

var patt=/pattern/modifiers; • pattern specifies the pattern of an

expression• modifiers specify if a search should be

global, case-sensitive, etc.

Page 288: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

289 /294

JavaScript RegExp ObjectRegExp Modifiers

• Modifiers are used to perform case-insensitive and global searches.

• The i modifier is used to perform case-insensitive matching.

• The g modifier is used to perform a global match (find all matches rather than stopping after the first match).

Page 289: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

290 /294

JavaScript RegExp ObjectRegExp Modifiers

• Example 1• Do a case-insensitive search for “Abdollahi" in a

string:var str="Visit abdollahi.us";var patt1=/Abdollahi/i;

• The marked text below shows where the expression gets a match:Visit abdollahi.us

Page 290: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

291 /294

JavaScript RegExp ObjectRegExp Modifiers

• Example 2• Do a global search for "is":

var str="Is this all there is?";var patt1=/is/g;

• The marked text below shows where the expression gets a match:Is this all there is?

Page 291: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

292 /294

JavaScript RegExp ObjectRegExp Modifiers

• Example 3• Do a global, case-insensitive search for "is":

var str="Is this all there is?";var patt1=/is/gi;

• The marked text below shows where the expression gets a match:Is this all there is?

Page 292: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

293 /294

JavaScript RegExp ObjectRegExp test() method

• The test() method searches a string for a specified value, and returns true or false, depending on the result.

• The following example searches a string for the character "e":

• Examplevar patt1=new RegExp("e");document.write(patt1.test("The best things in life are free"));

• Since there is an "e" in the string, the output of the code above will be:true

Page 293: Java Script Tutorial

By M

. A

bd

olla

hi

ww

w.a

bd

olla

hi.

us

294 /294

JavaScript RegExp ObjectRegExp exec() method

• The exec() method searches a string for a specified value, and returns the text of the found value. If no match is found, it returns null.

• The following example searches a string for the character "e":

• Example 1var patt1=new RegExp("e");document.write(patt1.exec("The best things in life are free"));

• Since there is an "e" in the string, the output of the code above will be:

Result : e