Java Script
Java Script
Java Script
JavaScript Basics
Client-side scripting generally refers to the class of computer programs on the web that are executed client-side, by the user's web browser, instead of server-side (on the web server). This type of computer programming is an important part of the Dynamic HTML (DHTML) concept, enabling web pages to be scripted; that is, to have different and changing content depending on user input, environmental conditions (such as the time of day), or other variables
Sometimes JavaScript is referred to as ECMAscript, ECMA is European Computer Manufacturers Association, it is a private organization that develops standards in information and communication systems.
2
Understanding Javascript
Advantages of Javascript
An Interpreted language Embedded within HTML Minimal Syntax Quick Development Designed for Simple, Small programs Performance Procedural capabilities Handling User events Easy Debugging and Testing Platform Independent
4
JavaScript Basics
Knowledge of basic HTML. You need a web browser. You need a editor. No need of special h/w or s/w or a web server.
Understanding Javascript
Javascript is a scripting language developed by Netscape. We can use nodepad, dreamweaver, golive .etc. for developing javascripts.
The easiest way to test a javascript program is by putting it inside an HTML page and loading it in a javascript enabled browser. You can integrate javascript code into the HTML file in three ways
Integrating under <head> tag Integrating under <body> tag Importing the external javascript.
7
Javascript in the head section will execute when called i.e javascript in the HTML file will execute immediately while the web page loads into the web browser before anyone uses it.
Integrating script under the <head> tag Syntax :<html> <head> <script type=text/javascript > ----------------</script> </head> <body> </body> <html>
9
When you place the javascript code under the <body> tag, this generates the content of the web page. Javascript code executes when the web page loads and so in the body section.
10
Integrating script under the <body> tag Syntax :<html> <head> </head> <body> <script type=text/javascript > ----------------</script> </body> <html>
11
You can import an external javascript file when you want to run the same javascript file on several HTML files without having to write the same javascript code on every HTML file. Save the external javascript file with an extension .js The external javascript file dont have a <script> tag.
12
The javascript code uses <script> </script> to start and end code. The javascript code bounded with the script tags is not HTML to be displayed but rather script code to be processed. Javascript is not the only scripting laguage, so you need to tell the browser which scripting language you are using so it knows how to process that language, so you specify <script type =text/javascript>
14
Including type attribute is a good practice but browsers like firefox, IE, etc. use javascript as their default script language, so if we dont specify type attribute it assumes that the scripting language is javascript. However use of type attribute is specified as mandatory by W3C.
15
Elements of javascript
Javascript statement
Every statement must end with a enter key or a semicolon. Example :<script type=text/javascript > document.write(First javascript stmt.); </script>
17
Elements of javascript
Several javascript statement grouped together in a statement block. Its purpose is to execute sequence of statements together. Statement block begins and ends with a curly brackets.
18
Elements of javascript
Example :<script type=text/javascript > { document.write(First javascript stmt.); document.write(Second javascript stmt.); }
</script>
19
Elements of javascript
Javascript comments
It supports both single line and multi line comments. // - Single line comments /*---------*/ - Multi line comments
20
Elements of javascript
Example :<script type=text/javascript > // javascript code { /* This code will write two statement in the single line. */ document.write(First javascript stmt.); document.write(Second javascript stmt.); } </script>
21
Variables
Syntax:- var variablename; Variable name can start with a alphabet or underscore. ( Rest characters can be number, alphabets, dollar symbol, underscore ) Do not use any special character other than dollar sign ($), underscore (_) Variable names are case-sensitive. Cannot contain blank spaces. Cannot contain any reserved word.
22
Naming conventions
Variables
Once you declare a variable you can initialize the variable by assigning value to it.
Syntax:- variablename=value;
You can also declare and initialize the variable at the same time.
Variables
<html> <head> <title> javascript variables </title> </head> <body> <script type=text/javascript> var bookname=web tech and applications; var bookprice=390; document.write(bookname is: ,bookname); document.write(bookprice is: ,bookprice); </script> </body> </html>
24
Datatypes
Javascript supports three primitive types of values and supports complex types such as arrays and objects.
Integer literals can be represented in decimal, hexadecimal and octal form. Floating literal consists of either a number containg a decimal point or an integer followed by an exponent.
25
Datatypes
Javascript automatically converts logical values true and false to 1 and 0 when they are used in numeric expressions.
26
Datatypes
String :consists of string values enclosed in single or double quotes. Examples: var first_name=Bhoomi; var last_name=Trivedi; var phone=4123778; var bookprice=450.40;
27
Operators
Arithmetic operators
Operator + Action Adds two numbers together Subtracts one number from another or changes a number to its negative
*
/ %
28
Operators
Addition
JavaScript can add together two or more numeric variables and/or numeric constants by combining them in an arithmetic expression with the arithmetic operator for addition ( + ). The result derived from evaluating an expression can be assigned to a variable for temporary memory storage. The following statements declare variables A and B and assign them numeric values; variable Sum is declared for storing the result of evaluating the arithmetic expression that adds these two variables. Example :var A = 20; var B = 10; var Sum = A + B; var Sum1 = 1 + 2; var Sum2 = A + 2 + B + 1; var Sum3 = Sum1 + Sum2;
29
Operators
Action
X++ The equivalent of X = X + 1; add 1 to X, replacing the value of X X-The equivalent of X = X - 1; subtract 1 from X, replacing the value of X X += Y The equivalent of X = X + Y; add Y to X, replacing the value of X X -= Y The equivalent of X = X - Y; subtract Y from X, replacing the value of X X *= Y The equivalent of X = X * Y; multiply Y by X, replacing the value of X
/=
30
Operators
Relational Operators
Conditional Operator == Comparison Equal operator. value1 == value2 Tests whether value1 is the same as value2. Not Equal operator. value1 != value2 Tests whether value1 is different from value2. Less Than operator. value1 < value2 Tests whether value1 is less than value2. Greater Than operator. value1 > value2 Tests whether value1 is greater than value2. Less Than or Equal To operator. value1 <= value2 Tests whether value1 is less than or equal to value2. Greater Than or Equal To operator. value1 >= value2 Tests whether value1 is greater than or equal to value2.
!=
<
>
<=
>=
31
Operators
Logical Operators
Logical Operator && Comparison
And operator. condition1 && condition2 The condition1 and condition2 tests both must be true for the expression to be evaluated as true. Or operator. condition1 || condition2 Either the condition1 or condition2 test must be true for the expression to be evaluated as true. Not operator. ! condition The expression result is set to its opposite; a true condition is set to false and a false condition is set to true.
32
||
If condition
33
If else condition
34
Nested if condition
Syntax:if (conditional expression) { if (conditional expression) { do this... } else { do this... } } else { if (conditional expression) { do this... } else { do this... } }
35
If..else if condition
Syntax:-
if (conditional expression1) { do this... } else if (conditional expression2) { do this... } else if (conditional expression3) { do this... } ... [else {do this...}]
36
Syntax:switch (expression) { case "value1": do this... break case "value2": do this... break ... [ default: do this... ] }
37
Iterations
For statement:for (exp1;exp2;exp3) { do this... } exp1:initial expression exp2:conditional expression exp3:incremental expression
38
Iterations
39
Iterations
40
Array
Array is a javascript object that is capable of storing a sequence of values. Array declaration syntax :
In the first syntax an array of size zero is created. In the second syntax size is explicitly specified, hence this array will hold a pre-determined set of values.
41
Array
Example :- bookname = new Array(); Note :- Even if array is initially created of a fixed length it may still be extended by referencing elements that are outside the current size of the array. Example :- cust_order = new Array(); cust_order[50] = Mobile; cust_order[100] = Laptop;
42
Array
Dense Array It is an array that has been created with each of its elements being assigned a specific value. They are declared and initialized at the same time. Syntax:- arrayname = new Array(value0,value1,..,valuen);
43
Array
Array is a javascript object so it has several methods associated with it. join() it returns all elements of the array joined together as a single string. By default , is used as a separator or you can specify the character to separate the array elements. reverse() it reverses the order of the elements in the array.
44
Array
Array is a javascript object so it has also properties associated with it. length - it determines the total number of elements. Example :- length = myarray.length;
Example :45
Special Operators
Strict Equal (= = =)
Example 5 == 5 true but 5 === 5 false It do not perform type conversion before testing for equality. Example :- condition ? Exp1 : Exp2
Ternary operators (? :)
Delete operator
It is used to delete a property of an object or an element at an array index. Example :- delete arrayname[5]
46
Special Operators
New operator
It is used to create an instance of object type. Example :- myarr = new Array(); It does not return a value It is specially used to return a URL with no value.
Void operator
47
Functions
Functions are blocks of JS code that perform a specific task and often return a value. Functions can be
Built in functions
Functions
eval
It is used to convert a string expression to a numeric value. Example :- var g_total = eval (10 * 10 + 5); It is used to convert a string value to an integer. It returns the first integer contained in a string or 0 if the string does not begin with an integer. Example :var str2no = parseInt(123xyz); //123 49 var str2no =parseInt(xyz); //NaN
parseInt
Functions
parseFloat
It returns the first floating point number contained in a string or 0 if the string does not begin with a valid floating point number. Example :var str2no = parseFloat(1.2xyz); //1.2
50
Functions
When defining user defined functions appropriate syntax needs to be followed for
Declaring functions Invoking / calling functions Passing values Returning and accepting the return values
51
Functions
Function Declaration
Functions are declared and created using the function keyword. A function can comprise of the following things, function name List of parameters Block of javascript code that defines what the function does. Syntax :function function_name( P1, P2,..,Pn) { // Block of JS code }
52
Functions
Place of declaration Functions can be declared any where within an HTML file. Preferably functions are created within the <head> tags. This ensures that all functions will be parsed before they are invoked or called.
53
Functions
If the function is called before it is declared and parsed, it will lead to an error condition as the function has not been evaluated and the browser does not know that it exists. Parsed:- it refers to the process by which the JS interpreter evaluates each line of script code and converts it into a pseudo compiled byte code before attempting to execute it.
At this time syntax errors and other programming mistakes that would prevent the script from running are trapped and reported.
54
Functions
Function call
A variable or a static value can be passed to a function. Example:printName(Bhoomi); var firstname=Bhoomi; printName(firstname);
55
Functions
Variable Scope
Any variable declared within the function is local to the function. Any variable declared outside the function is available to all the statements within the JS code.
Return Values
Use return statement to return a value or expression that evaluates to a single value. function cube(n) { var ans = n * n * n; return ans; }
56
Functions
Recursive Functions A function calls itself. Example :function factorial(n) { if ( n >1 ) return n * factorial(n-1); else return n; }
57
Dialog Boxes
Dialog Boxes JS provides the ability to pickup user input, display text to user by using dialog boxes. These dialog boxes appear as separate windows and their content depends on the information provided by the user. These content is independent of the text in the HTML page containing the JS code and does not affect the content of the page in any way. There are three types of dialog boxes provided by JS,
Dialog Boxes
Alert dialog box It is used to display small amount of textual output to a browser window. The alert DB displays the string passed to the alert() as well as an OK button. It is used to display a cautionary message or some information for eg.
Display message when incorrect information is keyed in a form. Display an invalid result as an output of a calculation. A warning that a service is not available on a given date/time.
59
Dialog Boxes
<html> <body> <script type=text/javascript> alert(This is a alert dialog box); document.write(Hello); </script> </ body > </html>
60
61
Dialog Boxes
Alert DB simply displays information in the browser and does not allow any interaction. It halts program execution until some action takes place. (i.e. click OK button) But it cannot be used to take input from user and display output based on it. For this we use prompt DB.
62
Dialog Boxes
It also causes program execution to halt until action takes place. (i.e OK or CANCEL )
Clicking OK causes the text typed inside the textbox to be passed to the program environment. Clicking CANCEL causes a Null value to be passed to the environment.
63
Dialog Boxes
<html> <body>
<script type=text/javascript> var name; name=prompt(Enter you Name: , ); document.write(<br/>Name entered is : ,name); </script> </ body > </html>
64
65
Dialog Boxes
It also causes program execution to halt until action takes place. (i.e OK or CANCEL )
Clicking OK causes true to be passed to the program, which called Confirm DB. Clicking CANCEL causes false to be passed to the program which called Confirm DB.
66
Dialog Boxes
<html> <body>
<script type=text/javascript> var ans; ans=confirm(Are you sure want to exit ? ); if ( ans == true ) document.write( you pressed OK); else document.write( you pressed CANCEL);
</script> </ body > </html>
67
68
In recent browsers several objects are made available to allow more control over a document. Eg :- navigator, window, document, form, etc. Several objects are part of JS language itself. These include the date, string and math objects. JS allows you to create your own objects that can contain related functionality.
Built-in objects
Custom objects
objectname.property objectname.method() Property :- alinkcolor, bgcolor, fgcolor, lastmodified, linkcolor, referrer, title, vlinkcolor.
Document object
Example :- document.lastModified
Form object
action- it points to the address of a program on the web server that will process the form data captured and being sent back. method it is used to specify the method used to send data captured by various form elements back to the web server.
73
text a text field ( <input type=text /> ) password a password field in which keystrokes appear as an asterisk ( <input type=password /> ) button it provides a button other than submit and reset. ( <input type=button /> ) checkbox a checkbox. ( <input type=checkbox /> ) radio a radio button. ( <input type=radio /> )
reset a reset button (<input type=reset /> ) submit a submit button ( <input type=submit /> ) select a selection list.
textarea a multiline text entry field. ( <textarea rows=n cols=n > </textarea>) hidden a field that may contain a value but is not displayed within a form. ( <input type=hidden /> )
value
Indicates the current status of the object. (checked/unchecked) defaultchecked Radio button , Indicates the default checkbox status of the element.
Events
Events
Event Handler
onclick
Event
The mouse button is clicked and released with the cursor positioned over a page element. The mouse button is double-clicked with the cursor positioned over a page element. The mouse button is pressed down with the cursor positioned over a page element. The mouse cursor is moved across the screen. The mouse cursor is moved off a page element. The mouse cursor is moved on top of a page element. The mouse button is released with the cursor positioned over a page element.
82
Example
<html> <head> <script type =text/javascript> function calculate(form){ form.result.value=eval(form.entry.value); } </script> </head> <body> <form> Enter a mathematical expression <input type=text name=entry /> <input type=button value=Calculate onClick=calculate(this.form) /> <input type=text name=result /> </form> </body> </html>
Built-in objects
String object
Every string in an javascript is an object. So it also has property and methods. Property : length
Description Returns the number of characters in a string: TextString.length "A text string".length Returns 13
Property length
Method bold()
Description Changes the text in a string to bold. TextString.bold() "A text string".bold()
Changes the text in a string to italic. TextString.italics() "A text string".italics() Changes the text in a string to strike-through characters. TextString.strike() "A text string".strike()
Returns
A text string
italics()
A text string
strike()
A text string
sub()
Changes the text in a string to subscript. "Subscript" + TextString.sub() "Subscript" + "A text string".sub()
Changes the text in a string to superscript. "Superscript" + TextString.sup() "Superscript" + "A text string".sup() Changes the text in a string to lower-case. TextString.toLowerCase() "A text string".toLowerCase()
sup()
toLowerCase()
a text string
toUpperCase()
Changes the text in a string to upper-case. TextString.toUpperCase() "A text string".toUpperCase() Changes the text in a string to fixed (monospace) font. TextString.fixed() "A text string".fixed() Changes the color of a string using color names or hexadecimal values. TextString.fontcolor("blue") TextString.fontcolor("#0000FF") "A text string".fontcolor("blue") "A textstring".fontcolor("#0000FF") Changes the size of a string using font sizes 1 (smallest) - 7 (largest). TextString.fontsize("4") "A text string".fontsize("4") Formats a string as a link. TextString.link("page.htm") "A text string".link("page.htm")
A TEXT STRING
fixed()
A text string
fontcolor ("color")
A text string
fontsize("n")
A text string
link("href")
A Text String
Method
charAt(index)
Description
Returns the character at position index in the string. TextString.charAt(0) "A text string".charAt(0) Returns the Unicode or ASCII decimal value of the character at position index in the string. TextString.charCodeAt(0) "A text string".charCodeAt(0) Returns the starting position of substring "chars" in the string. If "chars" does not appear in the string, then -1 is returned. TextString.indexOf("text") "A text string".indexOf("text") TextString.indexOf("taxt") Returns the starting position of substring "char" in the string, counting from end of string. If "chars" does not appear in the string, then -1 is returned. TextString.lastIndexOf("text") "A text string".lastIndexOf("text") TextString.lastIndexOf("taxt")
Returns
A
charCodeAt(index)
65
indexOf("chars")
2 2 -1
lastIndexOf("chars")
2 2 -1
substr(index[,length])
Returns a substring starting at position index and including length characters. If no length is given, the remaining characters in the string are returned. TextString.substring(7,6) "A text string".substring(7,6) Returns a substring starting at position index1 and ending at (but not including) position index2. TextString.substring(7,13) "A text string".substring(7,13) Converts a value to a string. var NumberValue = 10 var StringValue = NumberValue.toString() Returns a string containing a number formatted to n decimal digits. var NumberValue = 10.12345 var StringValue = NumberValue.toFixed(2) Returns a string containing a number formatted to n total digits. var NumberValue = 10.12345 var StringValue = NumberValue.toPrecision(5)
string
substring(index1,index2)
string
toString()
10
toFixed(n)
10.12
toPrecision(n)
10.123
Math object
E - Euler's constant LN2 - Natural log of the value 2 LN10 - Natural log of the value 10 LOG2E - The base 2 log of euler's constant (e). LOG10E - The base 10 log of euler's constant (e). PI - 3.1428 - The number of radians in a 360 degree circle (there is no other circle than a 360 degree circle) is 2 times PI. SQRT2 - The square root of 2.
Math object
Math.abs(expression)
Math.max(expr1,expr2) Returns the greater of two numbers: Math.max(10,20) Math.min(expr1,expr2) Returns the lesser of two numbers: Math.min(10,20)
20
10
Math object
Math.round(expression) Returns a number rounded to nearest integer (.5 rounds up): Math.round(1.25) Math.round(1.50) Math.round(1.75) Returns the next highest integer value above a number: Math.ceil(3.25) Returns the next lowest integer value below a number: Math.floor(3.25) Returns the y power of x: Math.pow(2,3) Returns the square root of a number: Math.sqrt(144) Returns a random number between zero and one: Math.random() 1 2 2
Math.ceil(expression)
Math.floor(expression)
8 12 0.039160
Date object
Method
getDate() getDay()
Description
Returns the day of the month. TheDate.getDate() Returns the numeric day of the week (Sunday = 0). TheDate.getDay() Returns the numeric month of the year (January = 0). TheDate.getMonth() Returns the current year. TheDate.getYear() TheDate.getFullYear()
Returns
4 4
getMonth()
getYear() getFullYear()
2013 2013
Date object
Method getTime() Description Returns the number of milliseconds since January 1, 1970. TheDate.getTime() Returns the military hour of the day. TheDate.getHours() Returns the minute of the hour. TheDate.getMinutes() Returns the seconds of the minute. TheDate.getSeconds() Returns 1280911017797
14
6 57 797
getMilliseconds()
Date object
Method
toTimeString()
Description
Converts the military time to a string. TheDate.toTimeString() Converts the time to a string. TheDate.toLocaleTimeString() Converts the date to an abbreviated string. TheDate.toDateString() Converts the date to a string. TheDate.toLocaleDateString() Converts the date and time to a string. TheDate.toLocaleString()
Returns
14:06:57 UTC+0530 09:45:48 UTC+0530 2:06:57 PM 9:45:48 AM
toLocaleTimeString() toDateString()
toLocaleDateString() toLocaleString()
Form Elements
TextBox <input type=text name=txtusr />
Properties name value defaultValue Methods focus() blur() select() Events onFocus() onBlur() onSelect() onChange()
Form Elements
Button <input type=button value=Click /> Submit <input type=submit value=Submit />
Form Elements
Checkbox <input type=checkbox name=chk />
Properties Methods Events
click()
onClick()
Form Elements
Textarea <textarea cols=20 rows=30> </textarea>
Properties name value defaultValue rows cols Methods focus() blur() select() Events onFocus() onBlur() onSelect()
Referencing Elements
The other way of referencing elements is as follows, Syntax :<tag id="id"...> The assigned id value must be unique within the document; that is, no two tags can have the same id. Also, the id value must be composed of alphabetic and numeric characters and must not contain blank spaces.
Referencing Elements
Once an id is assigned, then the HTML object can be referenced in a script using the notation as follows, Syntax :document.getElementById("id")
The style properties associated with particular HTML tags are referenced by appending the property name to the end of the object referent. Syntax :
Applying Methods
Methods are behaviors that elements can exhibit, it can be referenced in a script using the notation as follows, Syntax:document.getElementById("id").method() Enter your name: <input id="Box" type="text"/> document.getElementById("Box").focus()
Examples
<script type="text/javascript"> function ChangeStyle() {
document.getElementById("MyTag").style.fontSize = "14pt"; document.getElementById("MyTag").style.fontWeight = "bold"; document.getElementById("MyTag").style.color = "red";
} </script> <body> <p id="MyTag" onclick="ChangeStyle()">This is a paragraph that has its styling changed. </p> </body>
Use of the self-referent keyword this can be combined with a function call to pass a self identity to a function . Syntax :- eventHandler="functionName(this) function functionName(objectName) { objectName.style.property = "value"; objectName.style.property = "value"; }
Examples
<script type="text/javascript"> function ChangeStyle(Mytag) {
MyTag.style.fontSize = "14pt"; MyTag.style.fontWeight = "bold"; MyTag.style.color = "red";
} </script> <body> <p onclick="ChangeStyle(this)">This is a paragraph that has its styling changed. </p> </body>
Examples
<script type="text/javascript"> function ChangeStyle(Sometag) { SomeTag.style.fontSize = "14pt"; SomeTag.style.fontWeight = "bold"; SomeTag.style.color = "red"; } </script> <body> <p onclick="ChangeStyle(this)">This is para1.</p> <p onclick="ChangeStyle(this)">This is para2.</p> </body>
Navigator object
The JavaScript navigator object is the object representation of the client internet browser or web navigator program that is being used. This object is the top level object to all others Properties :- userAgent, appVersion, cookieEnabled Methods :- javaEnabled(), tiantEnabled() Navigator Objects
Window object
The JavaScript Window Object is the highest level JavaScript object which corresponds to the web browser window. Internal Objects :- window, self, parent, top
Window
Properties Methods Events
History object
The JavaScript History Object is property of the window object. Properties :- current , length, next, previous Methods :- back(), forward(), go() Example :<FORM> <INPUT TYPE="button" VALUE="Go Back" onClick="history.back() /> </FORM>
Frame object
The JavaScript Frame object is the representation of an HTML FRAME which belongs to an HTML FRAMESET. The frameset defines the set of frame that make up the browser window. The JavaScript Frame object is a property of the window object.
Document
Properties frames name length parent self Methods blur() onBlur focus() onFocus setInterval() clearInterval() setTimeout(exp, milliseconds) clearTimeout(timeout) Events
Document object
The JavaScript Document object is the container for all HTML HEAD and BODY objects associated within the HTML tags of an HTML document.
Document
Properties alinkcolor bgcolor, fgcolor, lastmodified, linkcolor, referrer, title, vlinkcolor Methods write() open() close() contextual() Events onClick ondblclick ondragstart onkeydown onkeypress ,onkeyup onmousedown ,onmousemove onMouseOut ,onMouseOver
Image object
Javascript Global
The JavaScript global properties and functions can be used with all the built-in JavaScript objects.
Property Description
Infinity
NaN
undefined
"Not-a-Number" value
Javascript Global
Function decodeURI() decodeURIComponent() encodeURI() encodeURIComponent() escape() eval() Description Decodes a URI Decodes a URI component Encodes a URI Encodes a URI component Encodes a string Evaluates a string and executes it as if it was script code
isFinite()
isNaN() Number()
parseFloat()
parseInt() String() unescape()
RegExp Object
A regular expression is an object that describes a pattern of characters. Regular expressions are used to perform patternmatching and "search-and-replace" functions on text. Regular expressions can be created in two ways as follows, Syntax :
RegExp Object
Modifiers
Description
Perform case-insensitive matching Perform a global match (find all matches rather than stopping after the first match)
RegExp Object
Brackets
[A-Z]
[a-z] [A-z] [adgk] [^adgk] (red|blue|green)
RegExp Object
Metacharacters
Metacharacter . \w \W \d \D
\s
\S \b \B
RegExp Object
Metacharacter \0 Description Find a NUL character
\n
\f \r \t \v \xxx
\xdd
\uxxxx
RegExp Object
Quantifiers
* is short for {0,}. Matches zero or more times. + is short for {1,}. Matches one or more times. ? is short for {0,1}. Matches zero or one time. E.g: /o{1,3}/ matches 'oo' in "tooth" and 'o' in "nose".
Quantifier
Description
n+
n* n? {n} {n,} {n,m} n$ ^n ?=n ?!n
RegExp Object
Description RegExp.exec(string)
Applies the RegExp to the given string, var match = /s(amp)le/i.exec("Sample text") and returns the match information. match then contains ["Sample","amp"] RegExp.test(string) Tests if the given string matches the Regexp, and returns true if matching, false if not. var match = /sample/.test("Sample text") match then contains false
String.match(pattern)
Matches given string with the RegExp. var str = "Watch out for the With g flag returns an array containing rock!".match(/r?or?/g) the matches, without g flag returns just the first match or if no match is str then contains ["o","or","ro"] found returns null.
RegExp Object
Description String.search(pattern) Matches RegExp with string and returns the index of the beginning of the match if found, -1 if not. String.replace(pattern,string) Replaces matches with the given string, and returns the edited string.
String.split(pattern) Cuts a string into an array, making cuts at matches. var str = "I am confused".split(/\s/g) str then contains ["I","am","confused"]
RegExp Object
Custom Object
Objects are useful to organize information. An object is just a special kind of data, with a collection of properties and methods. Example
A person is an object. Properties are the values associated with the object. The persons' properties include name, height, weight, age, skin tone, eye color, etc. Objects also have methods. Methods are the actions that can be performed on objects. The persons' methods could be eat(), sleep(), work(), play(), etc.
Custom Object
Properties
objName.propName
You can add properties to an object by simply giving it a value. Assume that the personObj already exists - you can give it properties named firstname, lastname, age, and eyecolor as follows:
Custom Object
Methods
An object can also contain methods. You can call a method with the following syntax: objName.methodName() Note: Parameters required for the method can be passed between the parentheses. To call a method called sleep() for the personObj:
personObj.sleep();
Custom Object
There are different ways to create a new object: The following code creates an instance of an object and adds four properties to it: personObj=new Object(); personObj.firstname=Rajiv"; personObj.lastname=Gandhi"; personObj.age=60; personObj.eyecolor="black";
Custom Object
2. Create a template of an object
Once you have the template, you can create new instances of the object, like this:
myson=new person(Rahul",Gandhi",30,"blue"); mydaughter=new person(Priyanka",Gandhi",32,"green");
Custom Object
You can also add some methods to the person object. This is also done inside the template:
Custom Object
Example
computearea() computediameter()
Custom Object
<html> <head> <script type="text/javascript" > function circle(r){ this.radius=r; this.computearea=computearea; this.computediameter=computediameter; } function computearea(){ var area=this.radius * this.radius * 3.14; return area } function computediameter(){ var diameter=this.radius * 2 ; return diameter; } </script></head>
Custom Object
<body> <script type="text/javascript" > var mycircle = new circle(20); alert("Area is " + mycircle.computearea()); alert("Diameter is " + mycircle.computediameter()); </script> </body> </html>
The try...catch statement allows you to test a block of code for errors. 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. We will see how to catch and handle JavaScript error messages, so you don't lose your audience.
The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs. Syntax :try { //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!
The throw statement allows you to create an exception. 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. Syntax :
throw(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!
In JavaScript you can add special characters to a text string by using the backslash sign.
Insert Special Characters The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters into a text string. var txt= Welcome to CICA which is a part of CHARUSAT document.write(txt); var txt= Welcome to \CICA\ which is a part of CHARUSAT document.write(txt);
Outputs
single quote double quote ampersand
\\
\n \r \t
backslash
new line carriage return tab
\b
\f
backspace
form feed
JavaScript For...In Statement The for...in statement loops through the elements of an array or through the properties of an object. Syntax for (variable in object) { code to be executed }