• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Java scripts
 

Java scripts

on

  • 4,016 views

Basic yet Important Knowledge of Java Script

Basic yet Important Knowledge of Java Script

Statistics

Views

Total Views
4,016
Views on SlideShare
3,981
Embed Views
35

Actions

Likes
0
Downloads
39
Comments
0

1 Embed 35

http://127.0.0.1 35

Accessibility

Categories

Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Java scripts Java scripts Document Transcript

    • How to Handle Simple Browsers ::-----------------------------------------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 shouldbe 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:<html><body><script type="text/javascript"><!--document.write("Hello World!");//--></script></body></html>The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This preventsJavaScript from executing the --> tag.JavaScript Where To================JavaScripts in the body section will be executed WHILE the page loads.JavaScripts in the head section will be executed when CALLED.Where to Put the JavaScriptJavaScripts in a page will be executed immediately while the page loads into the browser. This is notalways what we want. Sometimes we want to execute a script when a page loads, other times when auser triggers an event.Scripts in <head>Scripts to be executed when they are called, or when an event is triggered, go in the head section.If you place a script in the head section, you will ensure that the script is loaded before anyone uses it.Example<html><head><script type="text/javascript">function message(){alert("This alert box was called with the onload event"); //It is used to show the Messagebox with content}</script></head><body onload="message()"></body></html>Scripts in <body>
    • ===============Scripts to be executed when the page loads go in the body section.If you place a script in the body section, it generates the content of a page.Example<html><head></head><body><script type="text/javascript">document.write("This message is written by JavaScript");</script></body></html>Scripts in <head> and <body>=======================You can place an unlimited number of scripts in your document, so you can have scripts in both the bodyand the head section.<html><head><script type="text/javascript">....</script></head><body><script type="text/javascript">....</script></body>Using an External JavaScript===================If you want to run the same JavaScript on several pages, without having to write the same script on everypage, you can write a JavaScript in an external file.Save the external JavaScript file with a .js file extension.Note: The external script cannot contain the <script> tag!To use the external script, point to the .js file in the "src" attribute of the <script> tag:Example<html><head><script type="text/javascript" src="xxx.js"></script></head><body></body></html>Note: Remember to place the script exactly where you normally would write the script!****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 exampleswithout the semicolon at the end.Note: Using semicolons makes it possible to write multiple statements on one line.JavaScript Blocks============JavaScript statements can be grouped together in blocks.Blocks start with a left curly bracket {, and ends with a right curly bracket }.The purpose of a block is to make the sequence of statements execute together.This example will write a heading and two paragraphs to a web page:Example<script type="text/javascript">{document.write("<h1>This is a heading</h1>");document.write("<p>This is a paragraph.</p>");document.write("<p>This is another paragraph.</p>");}</script>Declaring (Creating) JavaScript Variables============================Creating variables in JavaScript is most often referred to as "declaring" variables.You can declare JavaScript variables with the var statement:var x;var carname;After the declaration shown above, the variables are empty (they have no values yet).However, you can also assign values to the variables when you declare them:var x=5;var carname="Volvo";After the execution of the statements above, the variable x will hold the value 5, and carname will hold thevalue Volvo.Note: When you assign a text value to a variable, use quotes around the value.Assigning Values to Undeclared JavaScript VariablesIf you assign values to variables that have not yet been declared, the variables will automatically bedeclared.These statements:x=5;carname="Volvo";have the same effect as:var x=5;var carname="Volvo";Redeclaring JavaScript Variables=======================
    • If you redeclare a JavaScript variable, it will not lose its original value.var x=5;var x;After the execution of the statements above, the variable x will still have the value of 5. The value of x isnot reset (or cleared) when you redeclare it.JavaScript ArithmeticAs with algebra, you can do arithmetic operations with JavaScript variables:y=x-5;z=y+5;The + Operator Used on Strings=======================The + operator can also be used to add string variables or text values together.To add two or more string variables together, use the + operator.txt1="What a very";txt2="nice day";txt3=txt1+txt2;After the execution of the statements above, the variable txt3 contains "What a verynice day".To add a space between the two strings, insert a space into one of the strings:txt1="What a very ";txt2="nice day";txt3=txt1+txt2;or insert a space into the expression:txt1="What a very";txt2="nice day";txt3=txt1+" "+txt2;After the execution of the statements above, the variable txt3 contains:"What a very nice day"Example :-<html><body><script type="text/javascript">x=5+5;document.write(x);document.write("<br />");x="5"+"5";document.write(x);document.write("<br />");x=5+"5";document.write(x);document.write("<br />");x="5"+5;document.write(x);document.write("<br />");</script><p>The rule is: If you add a number and a string, the result will be a string.</p>
    • </body></html>Output :-10555555The rule is: If you add a number and a string, the result will be a string.JavaScript Comparison and Logical Operators===============================Comparison and Logical operators are used to test for true or false.Comparison OperatorsComparison operators are used in logical statements to determine equality or difference betweenvariables or values.Given that x=5, the table below explains the comparison operators:Operator Description Example== is equal to x==8 is false=== is exactly equal to (value and type) x===5 is truex==="5" is false!= is not equal x!=8 is true> is greater than x>8 is false< is less than x<8 is true>= is greater than or equal to x>=8 is false<= is less than or equal to x<=8 is trueHow Can it be UsedComparison operators can be used in conditional statements to compare values and take actiondepending on the result:if (age<18) document.write("Too young");You will learn more about the use of conditional statements in the next chapter of this tutorial.Logical OperatorsLogical 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:Operator Description Example&& and (x < 10 && y > 1) is true|| or (x==5 || y==5) is false! not !(x==y) is trueConditional OperatorJavaScript also contains a conditional operator that assigns a value to a variable based on somecondition.Syntaxvariablename=(condition)?value1:value2
    • Examplegreeting=(visitor=="PRES")?"Dear President ":"Dear "; //No SpaceIf the variable visitor has the value of "PRES", then the variable greeting will be assigned the value "DearPresident " else it will be assigned "Dear".JavaScript If...Else Statements======================== * if statement - use this statement to execute some code only if a specified condition is true * if...else statement - use this statement to execute some code if the condition is true and another codeif the condition is false * if...else if....else statement - use this statement to select one of many blocks of code to be executed * switch statement - use this statement to select one of many blocks of code to be executedExample :if and if else ::if (condition) { code to be executed if condition is true }else { code to be executed if condition is not true }if else if ::if (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 condition1 and condition2 are not true }Swich Case ::switch (favoritemovie){case "Titanic":alert("Not a bad choice!")break;case "Water World":alert("No comment")break;case "Scream 2":alert("It has its moments")break;default : alert("Im sure it was great");}
    • JavaScript Popup BoxesAlert Box======================JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.Alert BoxAn 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");Example<html><head><script type="text/javascript">function show_alert(){alert("I am an alert box!");}</script></head><body><input type="button" onclick="show_alert()" value="Show alert box" /></body></html>Confirm 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");Example<html><head><script type="text/javascript">function show_confirm(){var r=confirm("Press a button");if (r==true) { document.write("You pressed OK!"); }else { document.write("You pressed Cancel!"); }
    • }</script></head><body><input type="button" onclick="show_confirm()" value="Show confirm box" /></body></html>Prompt 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 enteringan 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");Example<html><head><script type="text/javascript">function show_prompt(){var name=prompt("Please enter your name","Harry Potter");if (name!=null && name!="") { document.write("Hello " + name + "! How are you today?"); }}</script></head><body><input type="button" onclick="show_prompt()" value="Show prompt box" /></body></html>Function :::===============word function is in lower casewith no parameter<html><head><script type="text/javascript">function displaymessage(){alert("Hello World!");}</script></head>
    • <body><form><input type="button" value="Click me!" onclick="displaymessage()" /></form></body></html>Function with return Type :<html><head><script type="text/javascript">function product(a,b){return a*b;}</script></head><body><script type="text/javascript">document.write(product(4,3));</script></body></html>The for Loop=========<html><body><script type="text/javascript">var i=0;for (i=0;i<=5;i++){document.write("The number is " + i);document.write("<br />");}</script></body></html>While Loop========<html><body><script type="text/javascript">var i=0;while (i<=5) { document.write("The number is " + i); document.write("<br />"); i++; }
    • </script></body></html>Do-While Lop============<html><body><script type="text/javascript">var i=0;do { document.write("The number is " + i); document.write("<br />"); i++; }while (i<=5);</script></body>The break Statement====================The break statement will break the loop and continue executing the code that follows after the loop (ifany).Example<html><body><script type="text/javascript">var i=0;for (i=0;i<=10;i++) { if (i==3) { break; } document.write("The number is " + i); document.write("<br />"); }</script></body></html>The continue Statement=======================The continue statement will break the current loop and continue with the next value.Example<html><body><script type="text/javascript">var i=0for (i=0;i<=10;i++) {
    • if (i==3) { continue; } document.write("The number is " + i); document.write("<br />"); }</script></body></html>JavaScript For...In Statement(For each Loop)=====================The for...in statement loops through the elements of an array or through the properties of an object.Syntaxfor (variable in object) { code to be executed }Note: The code in the body of the for...in loop is executed once for each element/property.Note: The variable argument can be a named variable, an array element, or a property of an object.ExampleUse the for...in statement to loop through an array:Example<html><body><script type="text/javascript">var x;var mycars = new Array();mycars[0] = "Saab";mycars[1] = "Volvo";mycars[2] = "BMW";for (x in mycars) { document.write(mycars[x] + "<br />"); }</script></body></html>Events (http://www.w3schools.com/jsref/jsref_events.asp) All events with discription=======================By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can bedetected by JavaScript.Every element on a web page has certain events which can trigger a JavaScript. For example, we canuse the onClick event of a button element to indicate that a function will run when a user clicks on thebutton. We define the events in the HTML tags.
    • 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 keystrokeNote: Events are normally used in combination with functions, and the function will not be executedbefore the event occurs!For a complete reference of the events recognized by JavaScript, go to our complete Event reference.onLoad and onUnloadThe onLoad and onUnload events are triggered when the user enters or leaves the page.The onLoad event is often used to check the visitors browser type and browser version, and load theproper version of the web page based on the information.Both the onLoad and onUnload events are also often used to deal with cookies that should be set when auser enters or leaves a page. For example, you could have a popup asking for the users name upon hisfirst 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!".onFocus, onBlur and onChangeThe 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 calledwhenever the user changes the content of the field:<input type="text" size="30" id="email" onchange="checkEmail()">onSubmitThe 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 theuser clicks the submit button in the form. If the field values are not accepted, the submit should becancelled. The function checkForm() returns either true or false. If it returns true the form will besubmitted, otherwise the submit will be cancelled:<form method="post" action="xxx.htm" onsubmit="return checkForm()">onMouseOver and onMouseOutonMouseOver and onMouseOut are often used to create "animated" buttons.Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event isdetected:<a href="http://www.w3schools.com" onmouseover="alert(An onMouseOver event);return false"><imgsrc="w3s.gif" alt="W3Schools" /></a>JavaScript - Catching Errors(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 developersbut not for users. When users see errors, they often leave the Web page.This chapter will teach you how to catch and handle JavaScript error messages, so you dont lose youraudience.The try...catch StatementThe try...catch statement allows you to test a block of code for errors. The try block contains the code tobe run, and the catch block contains the code to be executed if an error occurs.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 JavaScripterror!Example 1The example below is supposed to alert "Welcome guest!" when the button is clicked. However, theres atypo in the message() function. alert() is misspelled as adddlert(). A JavaScript error occurs. The catchblock catches the error and executes a custom code to handle it. The code displays a custom errormessage informing the user what happened:Example<html><head><script type="text/javascript">var txt=""function message(){try { adddlert("Welcome guest!"); }catch(err) { txt="There was an error on this page.nn"; txt+="Error description: " + err.description + "nn"; txt+="Click OK to continue.nn"; alert(txt); }}</script></head><body><input type="button" value="View message" onclick="message()" /></body></html>The next example uses a confirm box to display a custom message telling users they can click OK to
    • continue viewing the page or click Cancel to go to the homepage. If the confirm method returns false, theuser clicked Cancel, and the code redirects the user. If the confirm method returns true, the code doesnothing:Example<html><head><script type="text/javascript">var txt=""function message(){try { adddlert("Welcome guest!"); }catch(err) { txt="There was an error on this page.nn"; txt+="Click OK to continue viewing this page,n"; txt+="or Cancel to return to the home page.nn"; if(!confirm(txt)) { document.location.href="http://www.w3schools.com/"; } }}</script></head><body><input type="button" value="View message" onclick="message()" /></body></html>JavaScript Special Characters===========================In JavaScript you can add special characters to a text string by using the backslash sign.Insert Special CharactersThe backslash () is used to insert apostrophes, new lines, quotes, and other special characters into a textstring.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 thestring above will be chopped to: We are the so-calledTo solve this problem, you must place a backslash () before each double quote in "Viking". Thisturns 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.Here is another example:document.write ("You & I are singing!");The example above will produce the following output:You & I are singing!The table below lists other special characters that can be added to a text string with the backslash sign:Code Outputs single quote" double quote& ampersand backslashn new liner carriage returnt tabb backspacef form feedJavaScript Guidelines============================Some other important things to know when scripting with JavaScript.JavaScript is Case SensitiveA function named "myfunction" is not the same as "myFunction" and a variable named "myVar" is not thesame as "myvar".JavaScript is case sensitive - therefore watch your capitalization closely when you create or call variables,objects and functions.White SpaceJavaScript ignores extra spaces. You can add white space to your script to make it more readable.The following lines are equivalent:name="Hege";name = "Hege";Break up a Code LineYou can break up a code line within a text string with a backslash. The example below will be displayedproperly:document.write("Hello World!");However, you cannot break up a code line like this:document.write ("Hello World!");JavaScript Objects Introduction=============================
    • JavaScript Objects Introductionprevious nextJavaScript is an Object Oriented Programming (OOP) language.An OOP language allows you to define your own objects and make your own variable types.Object Oriented ProgrammingJavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to defineyour own objects and make your own variable types.PropertiesProperties 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 ofcharacters in a string:<script type="text/javascript">var txt="Hello World!";document.write(txt.length);</script>The output of the code above will be:12JavaScript Objects IntroductionJavaScript is an Object Oriented Programming (OOP) language.An OOP language allows you to define your own objects and make your own variable types.Object Oriented ProgrammingJavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to defineyour own objects and make your own variable types.However, creating your own objects will be explained later, in the Advanced JavaScript section. We willstart by looking at the built-in JavaScript objects, and how they are used. The next pages will explain eachbuilt-in JavaScript object in detail.Note that an object is just a special kind of data. An object has properties and methods.Properties==================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 ofcharacters 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
    • Methods================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 inuppercase letters:<script type="text/javascript">var str="Hello world!";document.write(str.toUpperCase());</script>The output of the code above will be:HELLO WORLD!String Functions :=================<html><body><script type="text/javascript">var txt="Hello World!";document.write("<p>Big: " + txt.big() + "</p>"); O/p Big: Hello World!document.write("<p>Small: " + txt.small() + "</p>"); O/p :Small: HelloWorld!document.write("<p>Bold: " + txt.bold() + "</p>"); O/p :Bold: HelloWorld!document.write("<p>Italic: " + txt.italics() + "</p>"); O/p :Italic: HelloWorld!document.write("<p>Blink: " + txt.blink() + " (does not work in IE)</p>"); O/p :Blink: HelloWorld! (does not work in IE) //here Hello World will continue blink !document.write("<p>Fixed: " + txt.fixed() + "</p>"); O/p: Fixed: Hello World!document.write("<p>Strike: " + txt.strike() + "</p>"); O/P:Strike: HelloWorld!document.write("<p>Fontcolor: " + txt.fontcolor("Red") + "</p>"); O/P:Fontsize: HelloWorld!document.write("<p>Fontsize: " + txt.fontsize(16) + "</p>"); Lowercase: helloworld!document.write("<p>Lowercase: " + txt.toLowerCase() + "</p>"); Uppercase: HELLOWORLD!document.write("<p>Uppercase: " + txt.toUpperCase() + "</p>");document.write("<p>Subscript: " + txt.sub() + "</p>"); Subscript: Hello World!// O/p is not shown in wordpad properlydocument.write("<p>Superscript: " + txt.sup() + "</p>"); Superscript: HelloWorld! //O/p is not shown in wordpad properly
    • document.write("<p>Link: " + txt.link("http://www.w3schools.com") + "</p>"); Link: Hello World//Now it becomes link now</script></body></html><html><body>String always starts from zero(0)index function=============<script type="text/javascript">var str="Hello world!";document.write(str.indexOf("Hello") + "<br />"); O/p : 1document.write(str.indexOf("World") + "<br />"); O/p : -1(because "W" not found its is"w")document.write(str.indexOf("world")); O/p : 6</script></body></html>match function=========It will return string/string portion whereever it will be found .........return null if not match<html><body><script type="text/javascript">var str="Hello world!";document.write(str.match("world") + "<br />"); worlddocument.write(str.match("World") + "<br />"); nulldocument.write(str.match("worlld") + "<br />"); nulldocument.write(str.match("world!")); world!</script></body></html>Replace Function===============it will replace stringit is necessary to pass the Forward slash in the starting and in the end of string that is need toreplace<html><body><script type="text/javascript">
    • var str="Visit Microsoft!";document.write(str.replace(/Microsoft/,"W3Schools")); Visit W3Schools!</script></body></html>Definition and usage=========================The constructor property is a reference to the function that created the object.::::::::::::::::Syntaxobject.constructorExampleIn this example we will show how to use the constructor property:<script type="text/javascript">var test=new String();if (test.constructor==Array){document.write("This is an Array");}if (test.constructor==Boolean){document.write("This is a Boolean");}if (test.constructor==Date){document.write("This is a Date");}if (test.constructor==String){document.write("This is a String");}</script>The output of the code above will be:This is a StringThe prototype property allows you to add properties and methods to an object. ::::::::::::::Syntaxobject.prototype.name=valueExampleIn this example we will show how to use the prototype property to add a property to an object:<script type="text/javascript">function employee(name,jobtitle,born){this.name=name;
    • this.jobtitle=jobtitle;this.born=born;}var fred=new employee("Fred Flintstone","Caveman",1970): /// employee is not the class while evenwe can creates its object and assign the values to its property and create too.employee.prototype.salary=null; /// created new propertyfred.salary=20000;document.write(fred.salary);</script>The output of the code above will be:20000The anchor() method is used to create an HTML anchor. ::::::::::::::::::::::::SyntaxstringObject.anchor(anchorname)Parameter Descriptionanchorname Required. Defines a name for the anchorExampleIn this example we will add an anchor to a text:<script type="text/javascript">var txt="Hello world!";document.write(txt.anchor("myanchor"));</script>The code above could be written in plain HTML, like this:<a name="myanchor">Hello world!</a>The charAt() method returns the character at a specified position::::::::::::::::::::::::::::::::::SyntaxstringObject.charAt(index)Parameter Descriptionindex Required. A number representing a position in the stringTips and NotesNote: The first character in the string is at position 0.ExampleIn the string "Hello world!", we will return the character at position 1:<script type="text/javascript">var str="Hello world!";document.write(str.charAt(1));
    • </script>The output of the code above will be:eThe charCodeAt() method returns the Unicode of the character at a specified position::::::::::::::::::::::SyntaxstringObject.charCodeAt(index)Parameter Descriptionindex Required. A number representing a position in the stringTips and NotesNote: The first character in the string is at position 0.ExampleIn the string "Hello world!", we will return the Unicode of the character at position 1:<script type="text/javascript">var str="Hello world!";document.write(str.charCodeAt(1));</script>The output of the code above will be:101The concat() method is used to join two or more strings.::::::::::::::::::::::::SyntaxstringObject.concat(stringX,stringX,...,stringX)Parameter DescriptionstringX Required. One or more string objects to be joined to a stringExampleIn the following example we will create two strings and show them as one using concat():<script type="text/javascript">var str1="Hello ";var str2="world!";document.write(str1.concat(str2));</script>The output of the code above will be:Hello world!The fromCharCode() takes the specified Unicode values and returns a string.:::::::::::::::::::SyntaxString.fromCharCode(numX,numX,...,numX)Parameter DescriptionnumX Required. One or more Unicode values
    • Tips and NotesNote: This method is a static method of String - it is not used as a method of a String object thatyou have created. The syntax is always String.fromCharCode() and notmyStringObject.fromCharCode().ExampleIn this example we will write "HELLO" and "ABC" from Unicode:<script type="text/javascript">document.write(String.fromCharCode(72,69,76,76,79));document.write("<br />");document.write(String.fromCharCode(65,66,67));</script>The output of the code above will be:HELLOABCThe lastIndexOf() method returns the position of the last occurrence of a specified string value,searching backwards from the specified position in a string.::::::SyntaxstringObject.lastIndexOf(searchvalue,fromindex)Parameter Descriptionsearch Required. Specifies a string value to search forfromindex Optional. Specifies where to start the search. Starting backwards in the stringTips and NotesNote: The lastIndexOf() method is case sensitive!Note: This method returns -1 if the string value to search for never occurs.ExampleIn this example we will do different searches within a "Hello world!" string:<script type="text/javascript">var str="Hello world!";document.write(str.lastIndexOf("Hello") + "<br />");document.write(str.lastIndexOf("World") + "<br />");document.write(str.lastIndexOf("world"));</script>The output of the code above will be:0-16The search() method is used to search a string for a specified value.::::::::::::::::
    • This method supports regular expressions. You can learn about the RegExp object in our JavaScripttutorial.SyntaxstringObject.search(searchstring)Parameter Descriptionsearchstring Required. The value to search for in a string. To perform a case-insensitive search addan i flagTips and NotesNote: search() is case sensitive.Note: The search() method returns the position of the specified value in the string. If no match was foundit returns -1.Example 1 - Standard SearchIn the following example we will search for the word "W3Schools":<script type="text/javascript">var str="Visit W3Schools!";document.write(str.search(/W3Schools/));</script>The output of the code above will be:6Note: In the following example the word "w3schools" will not be found (because the search()method is case sensitive):<script type="text/javascript">var str="Visit W3Schools!";document.write(str.search(/w3schools/));</script>The output of the code above will be:-1The slice() method extracts a part of a string and returns the extracted part in a newstring.::::::::::::::::::SyntaxstringObject.slice(start,end) /// It is based on position not on length unlike substring(based onlength see below)Parameter Descriptionstart Required. Specify where to start the selection. Must be a number. Starts at 0end Optional. Specify where to end the selection. Must be a numberTips and NotesTip: You can use negative index numbers to select from the end of the string.
    • Note: If end is not specified, slice() selects all characters from the specified start position and to the end ofthe string.Example 1In this example we will extract all characters from a string, starting at position 0:<script type="text/javascript">var str="Hello happy world!";document.write(str.slice(0));</script>The output of the code above will be:Hello happy world!Example 2In this example we will extract all characters from a string, starting at position 6:<script type="text/javascript">var str="Hello happy world!";document.write(str.slice(6));</script>The output of the code above will be:happy world!Example 3In this example we will extract only the first character from a string:<script type="text/javascript">var str="Hello happy world!";document.write(str.slice(0,1));</script>The output of the code above will be:HThe split() method is used to split a string into an array of strings.::::::::::::;;SyntaxstringObject.split(separator, howmany)Parameter Descriptionseparator Required. Specifies the character, regular expression, or substring that is used todetermine where to split the stringhowmany Optional. Specify how many times split should occur. Must be a numeric valueTips and NotesNote: If an empty string ("") is used as the separator, the string is split between each character.Example
    • In this example we will split up a string in different ways:<script type="text/javascript">var str="How are you doing today?";document.write(str.split(" ") + "<br />");document.write(str.split("") + "<br />");document.write(str.split(" ",3));</script>The output of the code above will be:How,are,you,doing,today?H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?How,are,youThe substr() method extracts a specified number of characters in a string, from a startindex.:::::::::::SyntaxstringObject.substr(start,length)Parameter Descriptionstart Required. Where to start the extraction. Must be a numeric valuelength Optional. How many characters to extract. Must be a numeric value.Tips and NotesNote: To extract characters from the end of the string, use a negative start number (This does not work inIE).Note: The start index starts at 0.Note: If the length parameter is omitted, this method extracts to the end of the string.Example 1In this example we will use substr() to extract some characters from a string:<script type="text/javascript">var str="Hello world!";document.write(str.substr(3));</script>The output of the code above will be:lo world!Example 2In this example we will use substr() to extract some characters from a string:<script type="text/javascript">var str="Hello world!";document.write(str.substr(3,7)); // Start from 3 and count 7 characters from there</script>
    • The output of the code above will be:lo worlJava Script Regular Expression :==========================JavaScript global Property ::::JavaScript global PropertyRegExp Object Reference Complete RegExp Object ReferenceDefinition and UsageThe global property is used to return whether or not the "g" modifier is used in the regular expression.The "g" modifier is set if the regular expression should be tested against all possible matches in the string.This property is "TRUE" if the "g" modifier is set, "FALSE" otherwise.SyntaxRegExpObject.global<html><body><script type="text/javascript">var str = "Visit W3Schools";var patt1 = new RegExp("s","g");if(patt1.global) { document.write("Global property is set"); }else { document.write("Global property is NOT set."); }</script></body></html>o/p Global property is setJavaScript ignoreCase PropertyJavaScript ignoreCase PropertyRegExp Object Reference Complete RegExp Object ReferenceDefinition and UsageThe ignoreCase property is used to return whether or not the "i" modifier is used in the regularexpression.The "i" modifier is set if the regular expression should ignore the case of characters.This property is "TRUE" if the "i" modifier is set, "FALSE" otherwise.SyntaxRegExpObject.ignoreCase
    • <html><body><script type="text/javascript">var str = "Visit W3Schools";var patt1 = new RegExp("S","i");if(patt1.ignoreCase) { document.write("ignoreCase property is set"); }else { document.write("ignoreCase property is NOT set."); }</script></body></html>o/p=ignoreCase property is setJavaScript input PropertyThe input property is the string the pattern match is performed.<html><body><script type="text/javascript">function getRegInput(){var patt1 = new RegExp("W3");var str = document.frm1.txtinput.value;patt1.test(str); ///????if(RegExp.input) { alert("The input is: " + RegExp.input); }else { alert("The input does not contain W3"); }}</script><form name="frm1">Enter some text and click outside:<input type="text" name="txtinput" onChange=getRegInput() /><br />Input will only show if text contains W3.</form></body></html>
    • JavaScript lastIndex PropertyThe lastIndex property specifies the index (placement) in the string where to start the next match.The index is a number specifying the placement of the first character after the last match.This property only works if the "g" modifier is set.SyntaxRegExpObject.lastIndex<html><body><script type="text/javascript">var str = "The rain in Spain stays mainly in the plain";var patt1 = new RegExp("ain", "g");for(i = 0; i < 4; i++) { patt1.test(str); document.write("ain found. index now at: " + patt1.lastIndex); document.write("<br />"); }</script></body></html>Output :ain found. index now at: 8ain found. index now at: 17ain found. index now at: 28ain found. index now at: 43JavaScript lastMatch PropertyThe lastMatch property is the last matched characters.SyntaxRegExp.lastMatch<html><body><script type="text/javascript">var str = "The rain in Spain stays mainly in the plain";var patt1 = new RegExp("ain", "g");for(i = 0; i < 4; i++) { patt1.test(str); document.write(RegExp.lastMatch); // document.write(" found. index now at: " + patt1.lastIndex); document.write("<br />"); }</script></body></html>
    • o/painainainainJavaScript leftContext Property(Nice)The leftContext property is the substring in front of the characters most recently matched.This property contains everything from the string from before the match.SyntaxRegExp.leftContext<html><body><script type="text/javascript">var str = "The rain in Spain stays mainly in the plain";var patt1 = new RegExp("ain", "g");for(i = 0; i < 4; i++) { patt1.test(str) document.write(RegExp.lastMatch); document.write(" found. Text before match: " + RegExp.leftContext); document.write("<br />"); }</script></body></html>o/p :ain found. Text before match: The rain found. Text before match: The rain in Spain found. Text before match: The rain in Spain stays main found. Text before match: The rain in Spain stays mainly in the plJavaScript multiline PropertyThe multiline property is used to return whether or not the "m" modifier is used in the regular expression.The "m" modifier is set if the regular expression should be tested against possible matches over multiplelines.This property is "TRUE" if the "m" modifier is set, "FALSE" otherwise.SyntaxRegExpObject.multiline<html><body>
    • <script type="text/javascript">var str = "Visit W3Schools";var patt1 = new RegExp("s","m");if(patt1.multiline) { document.write("Multiline property is set"); o/p multiline property is set }else { document.write("Multiline property is NOT set."); }</script></body></html>JavaScript rightContext PropertyThe rightContext property is the substring from after the characters most recently matched.This property contains everything from the string from after the match.SyntaxRegExp.rightContext<html><body><script type="text/javascript">var str = "The rain in Spain stays mainly in the plain";var patt1 = new RegExp("ain", "g");for(i = 0; i < 4; i++) { patt1.test(str); document.write(RegExp.lastMatch); document.write(" found. Text after match: " + RegExp.rightContext); document.write("<br />"); }</script></body></html>ain found. Text after match: in Spain stays mainly in the plainain found. Text after match: stays mainly in the plainain found. Text after match: ly in the plainain found. Text after match:JavaScript source PropertyThe source property is used to return the text used for pattern matching.The returned text is everything except the forward slashes and any flags.SyntaxRegExpObject.source<html>
    • <body><script type="text/javascript">var str = "Visit W3Schools";var patt1 = new RegExp("W3S","g");document.write("The regular expression is: " + patt1.source);</script></body></html>o/p::The regular expression is: W3SJavaScript compile() MethodThe compile() method is used to change the regular expression.SyntaxRegExpObject.compile(regexp)Parameter Descriptionregexp Required. The new regular expression to search forExampleIn the following example we change the pattern from "Microsoft" to "W3Schools", and then test if we findthe specified pattern in a string:<script type="text/javascript">var str="Visit W3Schools";var patt=new RegExp("Microsoft");document.write("Test if we find " + patt + " in " + str + ": ")if (patt.test(str)==true) { document.write("Match found!") }else { document.write("Match not found") }patt.compile("W3Schools");document.write("<br />")document.write("Test if we find " + patt + " in " + str + ": ")if (patt.test(str)==true) { document.write("Match found!") }else { document.write("Match not found") }
    • </script>The output of the code above will be:Test if we find /Microsoft/ in Visit W3Schools: Match not foundTest if we find /W3Schools/ in Visit W3Schools: Match found!JavaScript exec() MethodThe exec() method searches a string for a specified value.This method returns the matched text if a match is found, and null if not.SyntaxRegExpObject.exec(string)Parameter DescriptionRegExpObject Required. The regular expression to usestring Required. The string to searchExampleIn the following example we will search for "W3Schools" in a string:<script type="text/javascript">var str="Visit W3Schools";var patt=new RegExp("W3Schools");document.write(patt.exec(str));</script>The output of the code above will be:W3SchoolsJavaScript test() MethodThe test() method searches a string for a specified value.This method returns true if a match is found, and false if not.SyntaxRegExpObject.test(string)Parameter DescriptionRegExpObject Required. The regular expression to usestring Required. The string to searchExampleIn the following example we change the pattern from "Microsoft" to "W3Schools", and then test if we findthe specified pattern in a string:<script type="text/javascript">var str="Visit W3Schools";var patt=new RegExp("Microsoft");
    • document.write("Test if we find " + patt + " in " + str + ": ")if (patt.test(str)==true) { document.write("Match found!") }else { document.write("Match not found") }patt.compile("W3Schools");document.write("<br />")document.write("Test if we find " + patt + " in " + str + ": ")if (patt.test(str)==true) { document.write("Match found!") }else { document.write("Match not found") }</script>The output of the code above will be:Test if we find /Microsoft/ in Visit W3Schools: Match not foundTest if we find /W3Schools/ in Visit W3Schools: Match found!JavaScript isFinite() FunctionThe isFinite() function is used to check if a value is a finite number.SyntaxisFinite(number)Parameter Descriptionnumber Required. The value to be testedExampleIn this example we use isFinite() to check for finite numbers:<script type="text/javascript">document.write(isFinite(123)+ "<br />");document.write(isFinite(-1.23)+ "<br />");document.write(isFinite(5-2)+ "<br />");document.write(isFinite(0)+ "<br />");document.write(isFinite("Hello")+ "<br />");document.write(isFinite("2005/12/12")+ "<br />");</script>
    • The output of the code above will be:truetruetruetruefalsefalseJavaScript Number() FunctionThe Number() function converts the value of an object to a number.SyntaxNumber(object)Parameter Descriptionobject Required. A JavaScript objectTips and NotesNote: If the parameter is a Date object, the Number() function returns the number of millisecondssince midnight January 1, 1970 UTC.Note: If the objects value cannot be converted to a number, the Number() function returns NaN.ExampleIn this example we will try to convert different objects to numbers:<script type="text/javascript">var test1= new Boolean(true);var test2= new Boolean(false);var test3= new Date();var test4= new String("999");var test5= new String("999 888");document.write(Number(test1)+ "<br />");document.write(Number(test2)+ "<br />");document.write(Number(test3)+ "<br />");document.write(Number(test4)+ "<br />");document.write(Number(test5)+ "<br />");</script>The output of the code above will be:101247394276301999NaNJavaScript isNaN() FunctionThe isNaN() function is used to check if a value is not a number.Syntax
    • isNaN(number)Parameter Descriptionnumber Required. The value to be testedExampleIn this example we use isNaN() to check some values:<script type="text/javascript">document.write(isNaN(123)+ "<br />");document.write(isNaN(-1.23)+ "<br />");document.write(isNaN(5-2)+ "<br />");document.write(isNaN(0)+ "<br />");document.write(isNaN("Hello")+ "<br />");document.write(isNaN("2005/12/12")+ "<br />");</script>The output of the code above will be:falsefalsefalsefalsetruetrueJavaScript escape() FunctionThe escape() function encodes a string, so it can be read on all computers.Syntaxescape(string)Parameter Descriptionstring Required. The string to be encodedTips and NotesNote: The escape() function encodes special characters, with the exception of:*@-_+./Tip: Use the unescape() function to decode strings encoded with escape().Note: The escape() and unescape() functions should not be used to encode or decode URIs. UseencodeURI() and decodeURI() functions instead!ExampleIn this example we use escape() to encode strings:<script type="text/javascript">document.write(escape("Visit W3Schools!") + "<br />");document.write(escape("?!=()#%&"));</script>
    • The output of the code above will be:Visit%20W3Schools%21%3F%21%3D%28%29%23%25%26JavaScript unescape() FunctionThe unescape() function decodes a string encoded with escape().Syntaxunescape(string)Parameter Descriptionstring Required. The string to be decodedTips and NotesNote: The escape() and unescape() functions should not be used to encode or decode URIs. UseencodeURI() and decodeURI() functions instead!ExampleIn this example we first encode the strings with the escape() function, and then decode them with theunescape() function:<script type="text/javascript">var test1="Visit W3Schools!";test1=escape(test1);document.write (test1 + "<br />");test1=unescape(test1);document.write(test1 + "<br />");</script>The output of the code above will be:Visit%20W3Schools%21Visit W3Schools!JavaScript eval() Function // Its important to make the code more smaller.......nice oneThe eval() function evaluates a string and executes it as if it was script code.Syntaxeval(string)Parameter Descriptionstring Required. The string to be evaluatedExampleIn this example we use eval() on some strings and see what it returns:<script type="text/javascript">
    • eval("x=10;y=20;document.write(x*y)");document.write("<br />");document.write(eval("2+2"));document.write("<br />");var x=10;document.write(eval(x+17));document.write("<br />");</script>The output of the code above will be:200427JavaScript String() FunctionThe String() function converts the value of an object to a string.SyntaxString(object)Parameter Descriptionobject Required. A JavaScript objectTips and NotesNote: The String() function returns the same value as toString() of the individual objects.ExampleIn this example we will try to convert different objects to strings:<script type="text/javascript">var test1= new Boolean(1);var test2= new Boolean(0);var test3= new Boolean(true);var test4= new Boolean(false);var test5= new Date();var test6= new String("999 888");var test7=12345;document.write(String(test1)+ "<br />");document.write(String(test2)+ "<br />");document.write(String(test3)+ "<br />");document.write(String(test4)+ "<br />");document.write(String(test5)+ "<br />");document.write(String(test6)+ "<br />");document.write(String(test7)+ "<br />");</script>The output of the code above will be:truefalse
    • truefalseSun Jul 12 2009 15:55:47 GMT+0530 (India Standard Time)999 88812345Examples for Events ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::JavaScript onclick Event<html><body>Field1: <input type="text" id="field1" value="Hello World!"><br />Field2: <input type="text" id="field2"><br /><br />Click the button below to copy the content of Field1 to Field2.<br /><button onclick="document.getElementById(field2).value=document.getElementById(field1).value">Copy Text</button></body></html>onfocus event<html><head><script type="text/javascript">function setStyle(x){document.getElementById(x).style.background="yellow";}</script></head><body>First name: <input type="text"onfocus="setStyle(this.id)" id="fname"><br />Last name: <input type="text"onfocus="setStyle(this.id)" id="lname"></body></html>onkeydown EventBrowser differences: Internet Explorer uses event.keyCode to retrieve the character that waspressed and Netscape/Firefox/Opera uses event.which.<html><body><script type="text/javascript">function noNumbers(e){
    • var keynum;var keychar;var numcheck;if(window.event) // IE { keynum = e.keyCode; }else if(e.which) // Netscape/Firefox/Opera { keynum = e.which; }keychar = String.fromCharCode(keynum);numcheck = /d/;return !numcheck.test(keychar);}</script><form>Type some text (numbers not allowed):<input type="text" onkeydown="return noNumbers(event)" /></form></body></html>Date and Time Section ::::<html><body><script type="text/javascript">document.write(Date());</script></body></html>o/p Sun Jul 12 2009 16:16:31 GMT+0530 (India Standard Time)<html><body><script type="text/javascript">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 = t/years;document.write("Its been: " + y + " years since 1970/01/01!");</script>
    • </body></html>O.p Its been: 39.554654748414514 years since 1970/01/01!<html><body><script type="text/javascript">var d = new Date();d.setFullYear(1992,10,3);document.write(d);</script></body></html>O/p :Tue Nov 03 1992 16:16:32 GMT+0530 (India Standard Time)<html><body><script type="text/javascript">var d = new Date();document.write (d.toUTCString());</script></body></html>Sun, 12 Jul 2009 10:46:34 GMT<html><body><script type="text/javascript">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";document.write("Today it is " + weekday[d.getDay()]); // getDay function will return the number
    • </script></body></html>Today is SundayClock<html><head><script type="text/javascript">function startTime(){var today=new Date();var h=today.getHours();var m=today.getMinutes();var s=today.getSeconds();// add a zero in front of numbers<10m=checkTime(m);s=checkTime(s);document.getElementById(txt).innerHTML=h+":"+m+":"+s;t=setTimeout(startTime(),500);}function checkTime(i){if (i<10) { i="0" + i; }return i;}</script></head><body onload="startTime()"><div id="txt"></div></body></html>return current time 16:39:02Mathematical Function :Mathematical MethodsIn addition to the mathematical constants that can be accessed from the Math object there are alsoseveral methods available.The following example uses the round() method of the Math object to round a number to the nearestinteger:document.write(Math.round(4.7));The code above will result in the following output:5
    • Random methodThe following example uses the random() method of the Math object to return a random number between0 and 1:document.write(Math.random());The code above can result in the following output:0.6388059778069849The following example uses the floor() and random() methods of the Math object to return a randomnumber between 0 and 10:document.write(Math.floor(Math.random()*11));The code above can result in the following output:4<html><body><script type="text/javascript">document.write(Math.random());</script></body></html><html><body><script type="text/javascript">document.write(Math.round(0.60) + "<br />");document.write(Math.round(0.50) + "<br />");document.write(Math.round(0.49) + "<br />");document.write(Math.round(-4.40) + "<br />");document.write(Math.round(-4.60));</script></body></html>The innerHTML property sets or returns the text of a link.It will redirect u to the microsoft site<html><head><script type="text/javascript">function changeLink(){document.getElementById(myAnchor).innerHTML="Visit W3Schools";
    • document.getElementById(myAnchor).href="http://www.w3schools.com";document.getElementById(myAnchor).target="_blank";}</script></head><body><a id="myAnchor" href="http://www.microsoft.com">Visit Microsoft</a><input type="button" onclick="changeLink()" value="Change link"><p>In this example we change the text and the URL of a hyperlink. We also change the target attribute.The target attribute is by default set to "_self", which means that the link will open in the same window.By setting the target attribute to "_blank", the link will open in a new window.</p></body></html>Regular Expression(RegExp)What is RegExpRegExp, is short for regular expression.When you search in a text, you can use a pattern to describe what you are searching for. RegExp IS thispattern.A simple pattern can be a single character.A more complicated pattern consists of more characters, and can be used for parsing, format checking,substitution and more.You can specify where in the string to search, what type of characters to search for, and more.Defining RegExpThe RegExp object is used to store the search pattern.We define a RegExp object with the new keyword. The following code line defines a RegExp object calledpatt1 with the pattern "e":var patt1=new RegExp("e");When you use this RegExp object to search in a string, you will find the letter "e".Methods of the RegExp ObjectThe RegExp Object has 3 methods: test(), exec(), and compile().test()The test() method searches a string for a specified value. Returns true or falseExamplevar 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:trueNavigator Object
    • Properties Description----------------------------------------------------------------------------------------------------appCodeName The code name of the browser.appName The name of the browser (ie: Microsoft Internet Explorer).appVersion Version information for the browser (ie: 4.75 [en] (Win98; U)).appMinorVersion The minor version number of the browser.cookieEnabled Boolean that indicates whether the browser has cookies enabled. cpuClass The type of CPU which may be "x86"language Returns the default language of the browser version (ie: en-US). NS and Firefox only.mimeTypes[] An array of all MIME types supported by the client. NS and Firefox only.platform[] The platform of the clients computer (ie: Win32).plugins An array of all plug-ins currently installed on the client. NS and Firefox only.systemLanguage Returns the default language of the operating system (ie: en-us). IE only.userAgent String passed by browser as user-agent header. (ie: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1))userLanguage Returns the preferred language setting of the user (ie: en-ca). IE only. mimeTypes An array of MIME type descriptive strings that are supported by the browser. onLine A boolean value of true or false.Image Map Example<html><head><script type="text/javascript">function writeText(txt){document.getElementById("desc").innerHTML=txt;}</script></head><body><img src ="planets.gif" width ="145" height ="126" alt="Planets" usemap="#planetmap" /><map name="planetmap"><area shape ="rect" coords ="0,0,82,126"onMouseOver="writeText(The Sun and the gas giant planets like Jupiter are by far the largestobjects in our Solar System.)"href ="sun.htm" target ="_blank" alt="Sun" /><area shape ="circle" coords ="90,58,3"onMouseOver="writeText(The planet Mercury is very difficult to study from the Earth becauseit is always so close to the Sun.)"href ="mercur.htm" target ="_blank" alt="Mercury" />
    • <area shape ="circle" coords ="124,58,8"onMouseOver="writeText(Until the 1960s, Venus was often considered a twin sister to theEarth because Venus is the nearest planet to us, and because the two planets seem to sharemany characteristics.)"href ="venus.htm" target ="_blank" alt="Venus" /></map><h4 id="desc"></h4></body></html>Timing Object<html><head><script type="text/javascript">function timedMsg(){var t=setTimeout("alert(5 seconds!)",5000);}</script></head><body><form><input type="button" value="Display timed alertbox!" onClick = "timedMsg()"></form><p>Click on the button above. An alert box will be displayed after 5 seconds.</p></body></html>