0% found this document useful (0 votes)
130 views28 pages

Wt-Unit-3 (Javascript)

Uploaded by

grojamani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views28 pages

Wt-Unit-3 (Javascript)

Uploaded by

grojamani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

III BSc,SEMESTER-6,PAPER-7Web-Technologies

Unit-III
Introduction To JavaScript
1. What is DHTML?
 DHTML means Dynamic Hypertext Markup Language
 DHTML is NOT a language.
 DHTML is a TERM describing the art of making dynamic and interactive web pages.
 DHTML combines HTML, JavaScript, the HTML DOM, and CSS.

2. What is a Java script?


Java Script is the object oriented scripting language. It was developed by Netscape
Communications. Java Script code is embedded in HTML and runs directly on the browser. It
works in all major web browsers, such as Internet Explorer, Fire fox, Google Chrome, Opera etc.
JavaScript was designed to add interactivity to HTML pages
It is a scripting language.(scripting language is a lightweight programming language)
It is usually embedded directly into HTML pages
It is an interpreted language (means that scripts execute without preliminary compilation)
History:
JavaScript's official name is ECMA Script. ECMA Script is developed and maintained by
the ECMA organization. ECMA-262 is the official JavaScript standard. The language was
invented by Brendan Each at Netscape (with Navigator 2.0), and has appeared in all Netscape
and Microsoft browsers since 1996. The development of ECMA-262 started in 1996, and the
first edition of were adopted by the ECMA General Assembly in June 1997. The standard was
approved as an international ISO (ISO/IEC 16262) standard in 1998. The development of the
standard is still in progress.
III BSc,SEMESTER-6,PAPER-7Web-Technologies
3. Difference between Java and JavaScript?
Java Java Script
Java is an Object Oriented Programming Java Script is the object oriented scripting
Language language
It is developed by Sun Microsystems It is developed by Netscape
It is capable of running on multiple operating Java Script code is embedded in HTML and
systems with the help of interpreter runs directly on the browser
The Java compiler converts the code into Java Script code is not compiled they are
byte code. directly run on the browser.
We can make stand-alone application with It is used for providing interactivity to the
the help of Java simple HTML pages
Java uses its own native code then executes it Java script code runs on the java script
on a virtual machine i.e. JVM. enabled browsers. The java script code is
interpreted by the java script engine.

4. What are the benefits and problems with Java Script?


The following are the benefits and problems in java script.
Benefits:
1. Java script is widely supported in all major web browsers.
2. It gives easy access to the document objects.
3. It can give the interesting animations.
4. It is relatively secure.
5. It doesn’t need a special plug-in to use scripts.
Problems:
1. If script doesn’t work then the page is useless.
2. Most scripts rely upon manipulating the elements of the DOM.
3. Scripts can run slowly and complex scripts can take long time to startup.

III BSc,SEMESTER-6,PAPER-7Web-Technologies
5. What are the alternatives of Java Script?
Java script is a powerful scripting language. There are lot of alternative scripting
languages are available now. Those are
 JScript (Microsoft)
 VBScript (Microsoft)
 PHP (While PHP originally stood for Personal Home Page, it is now said to stand for
PHP: Hypertext Preprocessor)
 CGI (Common Gateway Interface)
 Dart (Google)
 GWT or Google Web Toolkit is a framework for developing client-side web applications
using Java.

6. Explain the structure of a Java Script program & explain how it is include in html
documents
Java script code resembles C language. The key points that you need to apply in all
scripts are listed below.
 Each line of code is terminated by a semicolon.
 Block of code must be surrounded by a pair of curly braces.
 A block of code is a set of instructions that are to be executed together as a unit.
 Functions have parameters, which are passed inside parenthesis.
 Variables are declared using a keyword var.
 Scripts require neither a main function nor an exit condition.
 Execution of a script starts from the first line of code and runs to the last line of code.
Including Java Script into on HTML document:
We can include script in a web page in two ways.
Way 1: if your script code is very small directly include in the pair of <HTML></HTML> tags
directly.
Ex:
<html>
<head>
<script type = “text/Javascript”> Code related to java script</script>
</head>
<body>
……..

III BSc,SEMESTER-6,PAPER-7Web-Technologies
……..
</body>
</html>
Way 2: If your scripts are complex, then write script language in a separate file and save it a
“filename. js” and include it in a separate HTML document as follow.
Ex:
<html>
<head>
<script type = “text/javascript” src= “filename.js”/>
</head>
<body>
……..
</body></html>

7. What are the data types that supports Java Script?


Java script supports only 4 data types. Those are Numeric, Strings, Boolean, and NULL.
i. Numeric data type: These are basic numbers. They can be integers or floating point values.
The data type of the resultant will be decided based on operands & operator.
Ex: 100, 4000, 40.56, 34.55
ii. Strings: These are collection chars that are not numbers. The values of a string can contain
spaces & can be totaled made by digits. Generally string is enclosed within double quotes.
Ex : var s= “KNR”, “TJPS College”
iii. Boolean: Boolean var’s hold the values true /false. These are used to hold the result of
conditional tests.
Ex: var Ch= True or False
iv. Null: A Null values means one that has not yet been decides. It doesn’t mean nil or zero.
Ex: var sp=NULL;
Scope rules: The scope of a variable is all parts of a program where it I visible.
In JavaScript variables can be either local or global. Global coping means that a variable
is available to all parts of the programme. Such variables are declared outside of any function.
Local variables are declared inside a function. They can be used by that function only.
III BSc,SEMESTER-6,PAPER-7Web-Technologies
8. Explain String Manipulation functions in Java Script with suitable examples?
String manipulation incomes joining of strings, splitting of strings and search through the
strings. In order to perform these manipulation function Java Script has the following functions.
i. Length: it returns the number of characters in the string. This is not a function. It is a property
of the string hence parenthesis are not required.
Ex: var name=”TJPS”;
document.writeln (“The length of the name is “ + name.Length ) ;
OP: The length of the name is 4
ii. Concatenation of strings:In java script, we can concatenate strings in two ways.
a) Adding two or more strings by placing a ‘+’ operator between the
strings. Ex: var firstname=”NAGU”;
var lastname=” K”;
var name=firstname + lastname;
b) By using Concat function.
Ex:var firstname=”NAGU”;
Var name=firstname.Concat (“. K”);
iii. Split: The split function breaks the string into pieces. These pieces are stored as array of
strings. In this function we can also set how many pieces it can be made (optional).
Ex: var name=”TJPS College, Guntur”;
var words=name.Split(“ “);
for( i=0; i < words.Length; i++)
document.writeln(words[i]);
iv. Substr(index [, length]): This function returns a substring which starts at the character
indicated by the index parameter. The substring continues either to the end of the string or for the
number of characters indicated by the parameter ‘length’.
Ex: var name=”TJPS College”; document.writeln(“The
substring is”+ name.substr(2,3));
v. Lowercase : It converts the all characters into lower case.
Ex: var name=”NAGU”;
document.writeln(“lower case name=”+name.Lowercase);
vi. Uppercase: It converts the all characters into upper case.
Ex: var name=”nagu”;
document.writeln(“lower case name=”+name.uppercase);
III BSc,SEMESTER-6,PAPER-7Web-Technologies
vii. Chart At (index): This function returns the character while at the position index in the
string.
Ex: var sname=”NAGESWARA RAO”;
document.writeln(sname.ChartAt(5))
;

viii. Index of (“Search” [, offset]): The string is searched for the string or quoted characters in
the first parameter. If the search is successful the index of the start of the target string is returned
otherwise it returns -1. The function starts search from the start of the string (offset=0) offset
may also be specified as argument.
Ex: var name = “TJPS College, Guntur”;
Var result= name.IndexOf(“Col”);
if(result==-1)
document.writeln(“String not found”);
else
document.writeln(“String found”);

9. Explain the Mathematical Functions in Java Script?


Mathematical functions and values are part of a built-in Java Script object called Math. All
functions and attributes used in mathematics must be accessed through this object only as
i. Abs(value): it returns the absolute value of the number passed into it.
Ex:Abs(-20);
Output:20
ii. ACos, ASin, ATan: It returns the Arc Cosine, Arc Sin, Arc Tan of the values passed
respectively in radians.
iii. Ceil (value):The ceil() method represents the ceiling function, which always rounds
numbers up to the nearest value.
Ex: alert(Math.ceil(25.5)); //outputs “26”
iv. Floor (value):The floor() method represents the floor function, which always rounds
numbers down to the nearest value.

v. Cos (value), sin (value), tan (value): It returns the Cosine, Sine, and Tangent values of
the values passed respectively.
vi. Log (value): It returns the natural logarithmic value of its argument.
vii. Max( val1, val2): It returns the biggest of the two passed values.
III BSc,SEMESTER-6,PAPER-7Web-Technologies
Ex: var itemMax = Math.max(3, 54, 32, 16);
alert(itemMax); //outputs “54”
viii. Min( val1, val2): It returns the smallest of the two passed values.
Ex: var itemMin = Math.min(3, 54, 32, 16);
alert(itemMin); //outputs “3”
ix. ParseInt(string[index]): It returns integer equivalent of the string passed in.
x. ParseFloat(string): It returns floating point number equivalent of the string passed in.
xi. POW(value power):The pow() method is used to raise a number to a given power, such
as raising 2 to the power of 10.
Ex: variNum = Math.pow(2, 10);
xii. Random(): It returns a pseudo random number between 0 and 1.
xiii. Round(value): It returns result of rounding its argument to the nearest integer.
Ex: alert(Math.round(25.5)); //outputs “26”
xiv. Sqrt(value): It returns the square root of the value passed in.
Ex: var itemNum = Math.sqrt(4);
alert(itemNum); //outputs “2”

10. Explain Conditional Statements with example?


Javascript supports two basic conditional statements. Those are if-else and switch.
The if Statement:
The if statement provides the capability to alter the course of a program’s execution
based on an expression that yields a logical value. If the logical value is true, a specified set of
statements is executed. If the logical value is false, the set of statements is skipped.
If statement comes in two forms.
Syntax of the First form:
If(condition)
{
Statements;
}

Ex: if(hour<12)
{
document.write(“Good morning”);}
III BSc,SEMESTER-6,PAPER-7Web-Technologies
The syntax of the second form of the if statement is similar to the firm form except that
an else clause is added.
Syn:
If(condition)
{
First set of statements;
}
else {
Second set of Statements ;
}
Ex:
If(hour<12) {
document.write(“Good Morning”);
} else
{ document.write(“Hello
”);
}
The Switch Statement:
The syntax of the switch statement as follows.
Switch(expression)
{
Case value1:
Statements
Break;
………………………..
………………………..
Case valuen:
Statements
Break;
Default:
Statements
}
III BSc,SEMESTER-6,PAPER-7Web-Technologies
The switch statement evaluates the expression and determines if any of the values
(value1 through value n) match the expression’s value. If one of them matches, then the
statements for that particular case are executed, and statement execution then continues after the
switch statement. If there is not matching value, then statements for the default case are
executed.

Ex:
<html>
<head> <title> Using the switch statement </title> </head>
<body>
<script type=”text/javascript”>
for(i=1;i<=3;++i)
{
Switch(i) {
Case 1:
Val=”One”; break;
Case 2:
Val=”Two”; break;
Case 3:
Val=”Three”; break;
Case 4:
Val=”Four”; break;
Case 5:
Val=”Five”; break;
default:
Val=”Unkown”;
}
document.writeln(Val + “<br>”);
}
</script>
</body>
</html>
III BSc,SEMESTER-6,PAPER-7Web-Technologies
11. Illustrate the Loop Statements in Java Script with suitable example?
Loop statements are used to repeat the execution of a set of statements while a particular
condition is true. JavaScript supports three types of loop statements: the While statement, the
do-while statement, the for statement.
The While Statement:
The While statement is a basic loop statement, used to repeat the execution of a set of
statements while a specified condition is true.
Syn:
while ( condition ) {
statements
}

Ex:
<html>
<head><title> Using While
Statement</title></head> <body>
<script type=”text/JavaScript”>
i=1;
while(i<7)
{
document.write(“<H” +i+ ”> This is a level “+i+” heading.
<H”+i+”>”); ++i;
}
</script>
</body></html>

The do-while Statement:


The do-while statement is similar to the while statement. The only difference is that the
looping condition is checked at the end of the loop instead of at the beginning. This ensures that
the enclosed statements are executed at least once.
Syn:
do {
Statements;
} while (condition);
III BSc,SEMESTER-6,PAPER-7Web-Technologies
Ex:
i=0;
do {
++i;
document.writeln(i + “<br>”);
} while (i<10);

The for Statement:


The for statement is similar to the while statement in that it repeatedly executes a set of
statements while a condition is true.
Syn: for(initialization Statement; condition; updatestatement)
{
Statements;
}
Ex:
<html>
<head>
<title> Using While Statement</title>
</head>
<body>
<script type=”text/JavaScript”>
for(i=1; i<7;++i)
{
document.write(“<H” +i+ “> This is a level “+ i
+” heading.</H”+i+”>”);
}
</script>
</body>
</html>
KADIRI NAGESWARA RAO M.C.A Department of Computer Science, T.J.P.S College, Guntur.
11
III BSc,SEMESTER-6,PAPER-7Web-Technologies
12. Explain the Operators available in Java Script?
An operator is used to transform one or more values into a single resultant value. The
values to which the operator applies are referred to as operands. The combination of an operator
and its operands is referred to as an expression.
The following are the operators in JavaScript
 Arithmetic
 Logical
 Comparison
 String
 Bit manipulation
 Assignment
 Conditional
Arithmetic Operators:
Arithmetic operators are used in mathematical calculations.
Operator Description
+ Addition
- Subtraction or unary negation
* Multiplication
/ Division
% Modulus
+ Increment and then return value
--Decrement and then return value

Logical Operators:
Logical operators are used to perform Boolean operations on Boolean operands, such as
logical and, logical or, and logical not. The logical operators supported by JavaScript as
follows.
Operator Description
& Logical And
||Logical or
!Logical not
KADIRI NAGESWARA RAO M.C.A Department of Computer Science, T.J.P.S College, Guntur.
12
III BSc,SEMESTER-6,PAPER-7Web-Technologies
Comparison Operators:
Comparison operators are used to determine whether two values are equal, or to compare
numerical values to determine which value is greater than the other.
Operator Description
= Equal
= Strictly equal
!= Not equal
!== Strictly not equal
< Less than
<= Less than or equal
> Greater than
>_ Greater than or equal

String Operators:
String operators are used to perform operations on strings. Java script currently supports
only the +string concatenation operator. It is used to join two strings together.

Bit Manipulation Operators:


Bit manipulation operators perform operations on the bit representation of a value, such
as shifting the bits to the right or the left.
Operator Description
& And
| Or
^ Exclusive or
< Left shift
> Sign-propagating right shift
>>>Zero-fill right shift
III BSc,SEMESTER-6,PAPER-7Web-Technologies
Assignment Operators:
Assignment operators are used to update the value of a variable.
Operator Description
= Sets the variable on the left of the = operator
+= Increments the variable on the left of the += operator by the value
of the expression on its right.
-+ Decrements the variable on the left of the -= operator by the value
of the expression on its right.

Other operators are *=, /=, %=, <<=, >>=, >>>=, &=, !=, ^=
The conditional Expression Ternary Operator:
The ternary operator takes three operands – a condition to be evaluated and two
alternative values to be returned based on the truth or falsity of the condition.
Condition ? value1 : value2

Special Operators:
i. The comma (,) operator:
This operator evaluates two expressions and returns the value of the second expression.
ii. The delete operator:
The delete operator is used to delete a property of an object or an element at an array
index.
iii. The new operator:
The new operator is used to create an instance of an object type.
iv. The Typeof operator:
The typeof operator returns a string value that identifies the type of an operand.

13. Explain about Arrays in Java Script?


An Array is an ordered set of data elements which can be accessed through a single
variable name. An array is made up of a set of slots with each slot assigned to a single data
element. We can access the data elements either sequentially by reading from the start of the
array, or by their index.
The Structure of an Array

Item One Item Two Item Three ..... Item N


III BSc,SEMESTER-6,PAPER-7Web-Technologies
Creating Arrays:
Arrays can be constructed in three different ways.
1. Declare a variable and pass it some elements in array format.
Ex:
var days = [“Mon”, “Tue”, “Wed”, “Thu”];
2. Create an Array object using the keyword new and a set of elements to store:
Ex:
var days = new Array(“Mon”, “Tue”, “Wed”, “Thu”);
3. An empty array object which has space for a number of elements can be created:
Ex: var days = new Array(4);
Adding Elements to an Array:
Array elements are accessed by their index. The index denotes the position of the element
in the array.
Var days[3]=”Mon”;

Access an Array:
We 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.
Ex: document.write(a[0]);

Modify 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:
A[0]=”Sat”;
Previously it contains “Mon”, and then we change the value by assigning the value to the
array.

14. Explain Object based Array functions in Java Script?


Actually Java Script Array is an Object. It contains different useful functions like
concat(), push() etc..
i. Concat(array2 [, array3 [, array N]]):
A list of arrays is concatenated onto the end of the array and a new array formed.
Ex:
var first = [“Mon”, “Tue”];
III BSc,SEMESTER-6,PAPER-7Web-Technologies
var second=[“Wed”, “Thu”];
var third=new Array (“An”, “Object”, “Array”);
var result= first.concat(second, third);
for(i=0; i<result.legth; i++)
document.write(result[i]);
ii. Join (string):
By using this function we can join all the elements in Array to form a string.
iii. pop():
This function removes the last element from the array and in doing so reduce the number
of elements in the array by one.
iv. push(element1 [, element2 [, element]]):
This function adds a list of items onto the end of the array. The items are separated using
commas in the parameter list.
v. reverse():
This function swaps all of the elements in the array so that which was first is last, and
vice versa.
vi. shift():
It removes the first element of the array and in so doing shortens its length by one.
vii. Slice(start, [, finish]):
By using this function we can extract a range of elements from an Array. It contains two
parameters. The first parameter specifies which you want remove; the last element you want is
specified in the second parameter.

viii. sort ():


This function sorts the Array elements into lexicographic, dictionary order. Elements in
the array which are not text are first converted to strings before the sort operation is performed.

ix. Splice (index, number [, element1 [, element2 [, elementN]]]):


Using this function we can remove some elements and at the same time adding some new
ones to the Array. It has two parameters and a unlimited number of optional ones.

x. unshift (element1, [, element2 [, elementN]]):


This function inserts a list of elements onto the front of the Array. The list of new
elements can have just one item.
III BSc,SEMESTER-6,PAPER-7Web-Technologies
15. Explain the Functions in the Java Script?
 Functions are named blocks of statements that are referenced and executed as a unit.
 Data that is required for the execution of a function may be passed as parameters to the
function.
 A function will be executed by an event or by a call.
 We may call a function from anywhere within a page or from other pages if the function
is embedded in an external JS file.
 Functions can be defined both in the <head> and in the <body> section of a document.
Defining functions: A function must be defined before it can be used.
function functionName (P1, P2, P3……. Pn)
{
Statements; }
The function Name is the name used to refer the function. The parameters are the names
of variables that receive the values passed to the function. The parameters that are passed to a
function are referred to as the function’s arguments.
Example:
<html>
<head>
<script type=”JavaScript”>
function displaymessage()
{
alert(“Hello world!”);
}
</script>
</head>
<body>
<form>
<input type=”button” value=”Click me!”

onclick = ”displaymessage()”> </form>

</body>
</html>

KADIRI NAGESWARA RAO M.C.A Department of Computer Science, T.J.P.S College, Guntur.
17
III BSc,SEMESTER-6,PAPER-7Web-Technologies
Return statement:
The return statement is used to specify the value that is returned from the function.
Example:
<html>
<head>
<script type=”javascript”>
function Add (a,b)
{
return a+b;
}
</script>
</head>
<body>
<script type=”javascript”>
document.write(add(30,55));
</script></body></html>

16. Explain Exception Handling in Java Script with an example?


Many object-oriented programming languages provide a mechanism for handling errors.
This mechanism is called exception handling. JavaScript 1.4 was the first version of the language
to include exception handling.
An exception in object-based programming is an object, created dynamically at run-time,
which encapsulates an error and some information about it. The exception handling contains two
parts. Those are throw and try…. catch.
Throw:
An exception is an object. It’s created using the standard new method. Once the
exception object exists, you need to do something with it. What you do is throw the exception,
that is you pass it back up the call stack until there’s a piece of code which can handle it. The
syntax of the throw is

do something
if an error happens
{
create a new exception object
III BSc,SEMESTER-6,PAPER-7Web-Technologies
throw the exception
}
Try….. catch:
A program is going to try to execute a block of statements. If exception is thrown by any
of those statements, execution of the whole block ceases and the program looks for a catch block
ceases and the program looks for a catch statement to handle the exception. try

{
Statement one
Statement two
Statement three
}
catch exception
{
Handle the exception
}

I BSc,SEMESTER-6,PAPER-7Web-Technologies
OBJECTS IN THE JAVA SCRIPT
1. How java Script supports object orientation?
JavaScript is not a complete programming language but, rather, it is a scripting language.
There are some object-oriented features that are not supported by JavaScript. JavaScript does not
support the features of inheritance, information hiding, encapsulation and classification that are
supported by other object-oriented programming languages.
Object based features supported by JavaScript:
It supports various features related to object based language and JavaScript is sometimes
referred to as an object-based programming language. The vital features which JavaScript
supports related to object based are:
Object Type:
JavaScript supports the development of object types and in this context JavaScript
supports both predefined and user-defined objects. It is possible to assign objects of any type to
any variable.
Object Instantiation:
To carry out the process of creating specific object instances available in JavaScript,
users can make use of a new operator. The object types are defined by properties and methods.
Properties of objects are used to access the data values contained in an object.

2. What are Regular Expressions and explain the creation of regular expressions in Java
Script?
Regular expressionsare very powerful tools for performing pattern
matches.We use regular expressions to search for matches on particular text.
In JavaScript, we can use regular expressions by creating instances of the regular
expressionobject, RegExp.
Creating Regular Expressions:
Regular expressions can be creating in two ways those are statically (when the script is
first parsed) and dynamically (at run-time).

A static expression is created as follows.


var RegularExpression = /pattern/
Dynamic patterns are created using the new keyword to create an instance of the RegExp class;
var RegularExpression = new RegExp("pattern");

The RegExp() method allows you to dynamically construct the search pattern as a string, and is
useful when the pattern is not known ahead of time.
Example: & Exercise:
<html>
<head>
<title> Regular Expression Example</title>
<script Type="text/JavaScript">
function checkpincode()
{
var re6digit=/^\d{6}$/
var str= document.myform.myinput.value;

if (str.search(re6digit)==-1)
alert("Please enter a valid 6 digit number inside form");
else
alert("Entered value is correct");
}
</script>
</head>
<body>
<form name="myform">
Enter valid Pincode (6 digits) : <input type="text" name="myinput"
size=15> <input type="button" onClick=" checkpincode()" value="check">
</form>
</body>
</html>
var re6digit=/^\d{5}$/
 ^ indicates the beginning of the string. Using a ^ metacharacter requires that the match start
at the beginning.
 \d indicates a digit character and the {5} following it means that there must be 5 consecutive
digit characters.
 $ indicates the end of the string. Using a $ metacharacter requires that the match end at the
end of the string.
JavaScript Regular Expressions have the following methods and properties.

RegExp Object Methods


 compile() : Change the regular expression
 exec() : Executes a search for a pattern within a string. If the pattern is not found, exec()
returns a null value. If it finds one or more matches it returns an array of the match results.
It also updates some of the properties of the parent RegExp object.
 test() : Tests a string for pattern matches. This method returns a Boolean that indicates
whether or not the specified pattern exists within the searched string. This is the most
commonly used method for validation. It updates some of the properties of the parent
RegExp object.
String Object Methods that supports Regular Expressions
 search(): Search a string for a specified value. Returns the position of the value
 match(): Search a string for a specified value. Returns an array of the found value(s)
 replace(): Replace characters with other characters
 split(): Split a string into an array of strings

3. What are Regular Expressions (RegExp) functions in Java Script?


There are a number of ways to implement a RegExp, some through methods belonging to
the String object, some through methods belonging to the RegExp object. Whether the regular
expression is declared through an object constructor or a literal makes no difference as to the
usage.
Regular expressions are manipulated using functions which belong to either the RegExp
or String classes.
“String” class functions:
1. match(pattern): Searches for a matching pattern. Returns an array holding the results, or null
if not match is found.
2. replace(pattern1, pattern2): Searches for pattern1. If the search is successful pattern1 is
replaced with pattern2.
3. search(pattern): Searches for a pattern in the string. If the match is successful, the index,
offset, of the start of the match is returned. If the search fails, the function returns -1.
4. split(Pattern): Splits the string into parts based upon the pattern, or regular expression, which
is supplied as a parameter.
“RegExp” class functions:
1.RegExp.exec(string): Applies the RegExp to the given string, and returns the match
information.

2.RegExp.test(string): Tests if the given string matches the Regexp, and returns true if
matching, false if not.

4. Explain the built-in objects in Java script? Briefly?


In Java script there are two types of build-in objects are available. Those are language
and Browser objects.
Language object contains the following objects.
i. Array object: The Array object is used to store multiple values in a single variable.
ii. Boolean object: The Boolean object is used to convert a non-Boolean value to a Boolean
value (true or false)
iii. Date object: The Date object is used to work with dates and times. Date objects are
created with new Date().
iv. Math object: The Math object allows you to perform mathematical tasks.
v. Number object: The Number object is an object is an object wrapper for primitive
numeric values.
vi. String object: The string object is used to manipulate a stored piece of text.
vii. RegExp object: A regular expression is an object that describes a pattern of characters.
Regular expressions are used to perform pattern-matching and “Search-and-replace”
functions on text.

i. The Document Object


ii. The Window Object
iii. The Form object
iv. The Browser Object
i. The Document Object:
A document is a webpage that is being either displayed or created. The document has a
number of properties that can be accessed by JavaScript and used to manipulate the content of
the page. Some properties can be used to create HTML pages while others may be used to
change the operation of the current page.
The following are the Properties and Methods.
Properties:
i. title: it shows the Title of current document
ii. location: URL of the current page
iii. lastModified: it returns the document's last modified date and time.

KADIRI NAGESWARA RAO M.C.A Department of Computer Science, T.J.P.S College, Guntur.
23
III BSc,SEMESTER-6,PAPER-7Web-Technologies
iv. referrer: URL of the page from which the user came
v. bgColor: hexadecimal representation of the page color.
vi. fgColor: hexadecimal representation of the text colour for the current page.
vii. linkColor, alinkColor, vlinkColor: hexadecimal representation of the colours used for
links
viii. forms[]: Array of forms on the current page.
ix. forms.length: the number of form objects on the page.
x. links[]: Array of links from the current page in the order in which they appear in the
document.
xi. links.length: the number of hyperlinks on the page.
xii. anchors[]: an array of named anchors (internal links)
xiii. anchors.length: number of anchors in the document.
xiv. images[], applets [], embeds[]: Array of images, Java applets and plug-in objects on the
current page.

Methods:
i. write(“String”): It writes an arbitrary string to the HTML document.
ii. writeln(“String”): It writes a string to the HTML document and terminate it with a new
line character.
iii. Clear(): It clears the current document.
iv. Close: It closes the document.

ii. The Window Object:


The browser window is a changeable object that can be addressed by JavaScript code.
The properties and methods of the window object are as follows.
Properties:
i. frames[]: An Array of frames stored in the order in which they are defined in the
document.
ii. frames.length: It shows the number of frames.
iii. self: It shows the current window
iv. opener: the window which opened the current window
v. parent: it show the parent of current window if using a frameset
vi. top: It is main window which creates all frames.
vii. status: It show the message in the status bar.

KADIRI NAGESWARA RAO M.C.A Department of Computer Science, T.J.P.S College, Guntur.
24
III BSc,SEMESTER-6,PAPER-7Web-Technologies
viii. defaultStatus: It sets the default message for the status bar.
ix. name:The name of the window if it was created using the open() method and a name was
specified.
Methods:
i. alert(‘String”): It open a box containing the message.
ii. blur(): It remove focus from current window
iii. confirm(“String”):It displays a message box with OK and Cancel buttons.
iv. focus(): It give focus to current window
v. prompt(“String”): It displays a prompt window with field for the user to enter a text
string.
vi. scroll(int, y): It move the current window to the chosen x,y location.
vii. open(“URL”, “name”, “Options string”):It opens a new window showing the page at
URL. The window is given the name of parameter two and its appearance may be
controlled by the options list.
viii. close(): It close the current window
iii. The Form object
Form object can be manipulated in two ways by using JavaScript. The data that is entered
onto your form can be checked at submission. Second we can actually build forms through
JavaScript.
Properties:
 name: the unique name of the form
 method: submission method in numeric form. 0 = GET, 1 = POST
 action: the action attribute of the form.
 target: if specified this is the target window for responses to the submission of the form.
 elements[]: an array containing the form elements in the order in which they are declared
in the document.
 length: the number of elements in the form.

Methods:
 submit(): it submits the form.
 reset(): it resets the form.
Event Handlers:
 onSubmit(method): actions to be performed as the form is submitted.
 onReset(method): any actions to perform as the form is reset.

KADIRI NAGESWARA RAO M.C.A Department of Computer Science, T.J.P.S College, Guntur.
25
III BSc,SEMESTER-6,PAPER-7Web-Technologies

Ex:
<html>
<head>
<script type = "text/javascript">
function validate()
{
var method = document.forms[0].method;
var action = document.forms[0].action;
var value = document.forms[0].elements[0].value;
if ( value != "Narasimha")
{
document.forms[0].reset();
}
else
{
alert ("Hai ");
}
}
</script>
</head>
<body>
<form method = "post">
<input type = "text" name = "user" size = "32" >
<input type = "submit" value = "press me"
onClick = "validate()">
</form>
</body></html>

iv. The Browser Object


The browser is a JavaScript object and can be queried from within your code. The
browser object is actually called the Navigator object. The following are properties.
 navigator.appcodeName:It is the internal name of the browser. For both major products
this is Mozilla, which was the name of the original Netscape Code Source.

 navigator.appName: This is the public name of the browser


 navigator.appVersion: The version number, platform on which the browser is running
and the verson of Navigator with which it is compatible.
 navigator.userAgent: The strings appCodeName and appVersion concatenated together.
 navigator.plugins: An array containing details of all installed plug-ins.
 navigator.mimeTypes:An array of all supported MIME types – useful if you need to
make sure that the browser can handle your data.

5. Write about event handling in Java Script?


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.
Examples of events:
 A mouse click
 A web page or an image loading
 Mouse 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!
For a complete reference of the events recognized by JavaScript, go to our complete JavaScript
reference.

onLoad 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.
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
III BSc,SEMESTER-6,PAPER-7Web-Technologies
time the visitor arrives at your page, you could have another popup saying something like:
"Welcome John Doe!".

onFocus, 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()">
onSubmit:
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="xxx.htm" onsubmit="return checkForm()">

onMouseOver and onMouseOut:


onMouseOver 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 is
detected.

<a href="http://www.w3schools.com" onmouseover="alert('AnonMouseOver event');


return false"><imgsrc="w3s.gif" alt="W3Schools" /></a>

You might also like