Sie sind auf Seite 1von 25

UNIT III

1. Mention the advantages of java/java script


i. Use sending data continuously File storage
ii. Massively parallel computing
iii. Smart forms – includes various controls like text box, radio button, text area control etc.
iv. Peer-to-Peer Interaction – used in various client/server model.
v. Games – Combine the ability to easily include networking in your programs with java‟s powerful graphics and you
have the recipe for truly awesome multiplayer games.
vi. Chat – Used in various chat applications.
vii. Whiteboards – Java programs are not limited to sending text and data across the network.
viii. A number of programmers have developed whiteboard software that allows users in diverse locations to draw on
their computers

2. What are Style Sheets?


Style sheets are collections of style information that are applied to plain text. Style information includes font attributes such
as type size, special effects (bold,italic,underline), color and alignment. Style sheets also provide broader formatting
instructions by specifying values for quantities such as line spacing and left and right margins.
There are 3 types are:
Embedded
Internal
External

3. List down the ways of including style information in a document.


i. 1.Linked Styles -Style information is read from a separate file that is specified in the <LINK> tag
ii. 2.Embedded Styles -Style information is defined in the document head using the <STYLE> and </STYLE> tags.
iii. 3.Inline Styles -Style information is placed inside an HTML tag and applies to all content between that tag and it
companion closing tag.

4. Define cascading.
Cascading refers to a certain set of rules that browsers use, in cascading order, to determine how to use the style information.
Such a set of rules is useful in the event of conflicting style information because the rules would give the browser a way to
determine which style is given precedence.

5. What are the style precedence rules when using multiple approaches?
Inline styles override both linked style sheets and style information stored in the document head with <STYLE> tag.
Styles defined in the document head override linked style sheets.
Linked style sheets override browser defaults.

6. Give the syntax to specify a characteristic in linked style sheet.


{Characteristic: value}
Multiple characteristic/value pairs should be separated by semicolons.

7. List down font characteristics permitted in style sheets.


i. 1.font-family
ii. 2.font-size
iii. 3.font-weight
iv. 4.font-style
v. 5.font-variant

8. Write a note on content positioning characteristic "Visibility".


Enables the document author to selectively display or conceal positioned content; Possible values are show or hide.

9. Define scriptlets.
Scriptlets enable you to create small, reusable web applications that can be used in any web page. Scriptlets are created using
HTML, scripting and Dynamic HTML. To include them in an HTML document use the <OBJECT> tag.

10. What does DHTML refer?


DHTML refers to collection of technologies, which makes HTML documents more dynamic and interactive.
11. What does data binding mean?
Data binding is DHTML feature that lets you easily bind individual elements in your document to data from another source
such as database or comma delimited text file.

12. What is meant by Plug-in?


A hardware or software module that adds a specific feature or service to a larger system. The idea is that the new component
simply plugs in to the existing system. For example, there are number of plug-ins for the Netscape Navigator browser that
enable it todisplay different types of audio or video messages. Navigator plug-ins are based on MIME filetypes.

13. MENTION THE TYPES OF SCRIPTING LANGUAGES


· JavaScript is a Scripting language (web site development environment) created by Netscape.
· Hence JavaScript works best with the Netscape suite of Client and Server products.
· JavaScript is the native scripting language of Netscape Navigator.
· VBScript is the native Scripting language of HTML.
14. SERVER SIDE SCRIPTING
· In Server side scripting the script program is executed at Server Side the required html program is
sent to the client.
· The job of the server is more in server side scripting
15. CLIENT SIDE SCRIPTING
· Here the script program is processed and executed in the client side itself.
· So that it reduces the burden of the server.

16. LIST THE ADVANTAGES OF JAVA SCRIPT


JavaScript is an object-oriented language that allows creation of interactive Web pages
JavaScript allows user entries, which are loaded into an HTML form to be processed as required

17. ADVANTAGES
i. It is an interpreted language, which requires no compilation steps.
ii. Embedded within HTML.
iii. Minimal Syntax – easy to learn
iv. Quick Development
v. Designed for simple, small programs
vi. High performance
vii. Procedural Capabilities – support facilities such as condition checking, looping and
viii. branching.

ix. Designed for programming user events – like VB Java Script is also based on Events.
x. Easy Debugging and Testing
xi. Platform Independence/ Architecture Neutral
xii. SYNTAX OF JAVASCRIPT PROGRAM
xiii. <HTML>
xiv. <HEAD>
xv. <SCRIPT language = “JavaScript”>
xvi. … body of the script program
xvii. </SCRIPT>
xviii. </HEAD>
xix. <BODY>
xx. <SCRIPT language = “JavaScript”>
xxi. body of the program.
xxii. </SCRIPT>
xxiii. </BODY>
xxiv. </HTML>
18. WHAT IS DENSE ARRAYS?
· A dense array is an array that has been created with each of its elements being assigned a specific
value.
· Dense arrays are used exactly in the same manner as other arrays.
· Dense arrays are declared and initialized at the same time.

Array Methods
Join() – returns all elements of the array joined together as a single string.
Reverse() – reverses the order of the elements in the array.

19. LIST COMPARISION OPERATORS & STRING OPERATORS IN JAVA


· = = equal (perform type conversion before testing for equality.
· = = = strictly equal (do not perform type conversion before testing for equality
STRING OPERATORS
Currently Java Script supports only one string concatenation (+) operator.
EXAMPLE
“ab” + “cd” produces “abcd”

20. LIST THE VARIOUS DIALOG BOXES IN JAVA SCRIPT


Dialog boxes are used to display small windows. This is also used to get input from user.

i. SYNTAX
ii. alert(“message”);
iii. alert(“Click here to continue”)
iv. prompt(“Enter your name”, name)
v. Alert is only used to display some information
vi. Prompt is used to display information along with some input value
vii. Confirm dialog box, causes program execution to halt until user action takes place.
viii. The user action can be either OK or CANCEL.
ix. OK – returns true
x. CANCEL – returns false
xi.

21. MENTION THE VARIOUS JAVA SCRIPT OBJECT MODELS .


· Math Object
· String Object
· Date Object
· Boolean and Number Object
· Document Object
· Window Object

22. HOW SCRIPTING LANGUAGE IS DIFFERS FROM HTML.


· HTML is used for simple web page design
· HTML with FORM is used for both form design and Reading input values from user.
· Scripting Language is used for Validating the given input values weather it is correct or not, if the
input value is incorrect, the user can pass an error message to the user.
· Using form concept various controls like Text box, Radio Button, Command Button, Text Area
control and List box can be created.

23. DEFINE FUNCTION IN JAVA SCRIPT .


Function is a part of a program or in other words function is a module in java program which can be called or invoked any
number of times from the main program.
Function can be called any number of times but it can accept any input values or parameters, however it can return only one
output at a time.

24. DEFINE CSS – CASCADING STYLE SHEET

· DHTML is a new and emerging technology that has evolved to meet the increasing demand for
eye-catching and mind-catching web sites.
· DHTML combines HTML with Cascading Style Sheets (CSS) and Scripting Languages. HTML
specifies a web page‟s elements like table, frame, paragraph, bulleted list, etc. CSS can be used to
determine an element‟s size, color, position and a number of other features.

· Scripting Languages (JavaScript and VBScript) can be used to manipulate the web page‟s
elements so that styles assigned to them can change in response to a user‟s input.

25. DEFINE CASDING STYLE SHEETS (CSS )


· CSS are powerful mechanism for adding styles (e.g. Fonts, Colors, Spacing) to web documents.
· They enforce standards and uniformity throughout a web site and provide numerous attributes to
create dynamic effects.
· The advantage of a style sheet includes the ability to make global changes to all documents from a
single location. Style sheets are said to cascade when they combine to specify the appearance of a
page.
The style assignment process is accomplished with the <STYLE>…</STYLE> tags.

26. MENTION THE TYPES OF STYLE SHEETS


i. 1 Embedded or Internal Style sheet
ii. 2 External or Linked Style sheet
iii. 3 Inline style sheet

27. LIST THE DIFFERENCE BETWEEN STYLE SHEETS


Slno „Embedded Linked Inline Style Sheet
Style program is Linked CSS files.
embedded with in the Explicit LINK statement Styles used in .CSS file can be
HTML program itself. is not needed. used in any HTML program
Style program alone is stored in Explicit LINK REL statement is Styles created should
a separate file with an extension needed to connect with .CSS file be used immediately
of Not required before creating
.css file. Styles can be used within another new style.
Different from the program only, it can
Embedded and not be called some other

28. LIST THE PROPERTIES OF STYLE TAG


<STYLE> tag properties are divided in to 6 categories. They are
 Font Attributes
 Color and Background attributes
 Text Attributes
 Border Attributes
 Margin Attributes and
 List Attributes.

29. HOW TO INTRODUCE STYLE IN HTML PROGRAM?


<HTML>
<HEAD>
<STYLE Type = “text/css”>
predefined tag name {attribute name1:attribute value1; attribute name2:attribute
value2; ……attribute name-n:attribute value-n}
<STYLE>
</HEAD>
<BODY>
write the body of program
</BODY> </HTML>

30. What are Style Sheets?


Style sheets are collections of style information that are applied to plain text. Style information
includes font attributes such as type size, special effects (bold,italic,underline), color and
alignment. Style sheets also provide broader formatting instructions by specifying values for
quantities such as line spacing and left and right margins.

31. List down the ways of including style information in a document.


1.Linked Styles -Style information is read from a separate file that is specified in the
<LINK> tag
2.Embedded Styles -Style information is defined in the document head using the
<STYLE> and </STYLE> tags.
3.Inline Styles -Style information is placed inside an HTML tag and applies to all
content between that tag and it companion closing tag.

32. What are the style precedence rules when using multiple approaches?
Inline styles override both linked style sheets and style information stored in the document head
with <STYLE> tag.

33. Give the syntax to specify a characteristic in linked style sheet.


{Characteristic: value}
Multiple characteristic/value pairs should be separated by semicolons.

34. List down font characteristics permitted in style sheets.


1.font-family
2.font-size
3.font-weight
4.font-style

35. Write a note on content positioning characteristic "Visibility".


Enables the document author to selectively display or conceal positioned content; Possible values
are show or hide.

36. List out the differences between Java script & VB script.
37. What is the advantage of client side programming?
38. List out the various client side programming languages.
39. What is java script?
40. What are the uses of Java script?
41. What is the use of prompt and confirm commands.
42. What are the various browsers to be supported .
43. Write a java script program to print first 100 numbers .
44. Write a java script program to print Armstrong numbers between 1 to 500.
45. Draw the DOM model.

PART-B
1.Explain string object used in JavaScript.
Java Script String Object:
The String object let's you work with a series of characters and wraps Javascript's string primitive data type with a
number of helper methods.
Because Javascript automatically converts between string primitives and String objects, you can call any of the
helper methods of the String object on a string primitive.
Syntax:
Creating a String object:

var val = new String(string);

The string parameter is series of characters that has been properly encoded.

String Properties:
Here is a list of each property and their description.
Property Description
constructor Returns a reference to the String function that created the object.

length Returns the length of the string.

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

String Methods
Here is a list of each method and its description.
Method Description

charAt() Returns the character at the specified index.

charCodeAt() Returns a number indicating the Unicode value of the character at the given index.

concat() Combines the text of two strings and returns a new string.

Returns the index within the calling String object of the first occurrence of the specified
indexOf()
value, or -1 if not found.

Returns the index within the calling String object of the last occurrence of the specified
lastIndexOf()
value, or -1 if not found.

Returns a number indicating whether a reference string comes before or after or is the same
localeCompare()
as the given string in sort order.

match() Used to match a regular expression against a string.

Used to find a match between a regular expression and a string, and to replace the matched
replace()
substring with a new substring.

search() Executes the search for a match between a regular expression and a specified string.

slice() Extracts a section of a string and returns a new string.

split() Splits a String object into an array of strings by separating the string into substrings.

Returns the characters in a string beginning at the specified location through the specified
substr()
number of characters.

substring() Returns the characters in a string between two indexes into the string.

The characters within a string are converted to lower case while respecting the current
toLocaleLowerCase()
locale.

The characters within a string are converted to upper case while respecting the current
toLocaleUpperCase()
locale.

toLowerCase() Returns the calling string value converted to lower case.

toString() Returns a string representing the specified object.

toUpperCase() Returns the calling string value converted to uppercase.

valueOf() Returns the primitive value of the specified object.


Eg:
<html>
<head>
<title>Character Processing Methods</title>

<script type = "text/javascript">


<!--
var s = "ZEBRA";
var s2 = "AbCdEfG";

document.writeln( "<p>Character at index 0 in '" +


s + "' is " + s.charAt( 0 ) );
document.writeln( "<br />Character code at index 0 in '"
+ s + "' is " + s.charCodeAt( 0 ) + "</p>" );

document.writeln( "<p>'" +
String.fromCharCode( 87, 79, 82, 68 ) +
"' contains character codes 87, 79, 82 and 68</p>" )

document.writeln( "<p>'" + s2 + "' in lowercase is '" +


s2.toLowerCase() + "'" );
document.writeln( "<br />'" + s2 + "' in uppercase is '"
+ s2.toUpperCase() + "'</p>" );
// -->
</script>

</head><body></body>
</html>

Output:

Character at index 0 in 'ZEBRA' is Z


Character code at index 0 in 'ZEBRA' is 90
'WORD' contains character codes 87, 79, 82 and 68
'AbCdEfG' in lowercase is 'abcdefg'
'AbCdEfG' in uppercase is 'ABCDEFG'

1. Explain “JavaScript as an Document Object Model (DOM)?


Every web page resides inside a browser window which can be considered as an object.
A Document object represents the HTML document that is displayed in that window. The Document object has
various properties that refer to other objects which allow access to and modification of document content.
The way that document content is accessed and modified is called the Document Object Model, or DOM. The
Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web
document.
 Window object: Top of the hierarchy. It is the outmost element of the object hierarchy.
 Document object: Each HTML document that gets loaded into a window becomes a document object. The
document contains the content of the page.
 Form object: Everything enclosed in the <form>...</form> tags sets the form object.
 Form control elements: The form object contains all the elements defined for that object such as text
fields, buttons, radio buttons, and checkboxes.
Here is a simple hierarchy of few important objects:

There are several DOMs in existence. The following sections explain each of these DOMs in detail and describe
how you can use them to access and modify document content.
 The Legacy DOM: This is the model which was introduced in early versions of JavaScript language. It is
well supported by all browsers, but allows access only to certain key portions of documents, such as forms,
form elements, and images.
Document Properties in Legacy DOM:
Here is the list of document properties which can be accessed using Legacy DOM:

Property Description & Example

Deprecated - A string that specifies the color of activated links.


alinkColor
Example: document.alinkColor

An array of Anchor objects, one for each anchor that appears in the document
anchors[ ]
Example: document.anchors[0], document.anchors[1] and so on

An array of Applet objects, one for each applet that appears in the document
applets[ ]
Example: document.applets[0], document.applets[1] and so on

Deprecated - A string that specifies the background color of the document.


bgColor
Example: document.bgColor

A string-valued property with special behavior that allows the cookies associated with this
Cookie document to be queried and set.
Example: document.cookie

A string that specifies the Internet domain the document is from. Used for security purpose.
Domain
Example: document.domain

An array of objects that represent data embedded in the document with the <embed> tag. A
synonym for plugins[ ]. Some plugins and ActiveX controls can be controlled with JavaScript
embeds[ ]
code.
Example: document.embeds[0], document.embeds[1] and so on
Deprecated - A string that specifies the default text color for the document
fgColor
Example: document.fgColor

An array of Form objects, one for each HTML form that appears in the document.
forms[ ]
Example: document.forms[0], document.forms[1] and so on

An array of Image objects, one for each image that is embedded in the document with the
images[ ] HTML <img> tag.
Example: document.images[0], document.images[1] and so on

A read-only string that specifies the date of the most recent change to the document
lastModified
Example: document.lastModified

Deprecated - A string that specifies the color of unvisited links


linkColor
Example: document.linkColor

links[ ]
links[ ]
Example: document.links[0], document.links[1] and so on

The URL of the document. Deprecated in favor of the URL property.


location
Example: document.location

A synonym for the embeds[ ]


plugins[ ]
Example: document.plugins[0], document.plugins[1] and so on

A read-only string that contains the URL of the document, if any, from which the current
referrer document was linked.
Example: document.referrer

The text contents of the <title> tag.


Title
Example: document.title

A read-only string that specifies the URL of the document.


URL
Example: document.URL

Deprecated - A string that specifies the color of visited links.


vlinkColor
Example: document.vlinkColor

Document Methods in Legacy DOM:


Here is the list of methods supported by Legacy DOM:

Property Description & Example

Deprecated - Erases the contents of the document and returns nothing.


clear( )
Example: document.clear( )

Closes a document stream opened with the open( ) method and returns nothing.
close( )
Example: document.close( )

Deletes existing document content and opens a stream to which new document
open( ) contents may be written. Returns nothing.
Example: document.open( )
Inserts the specified string or strings into the document currently being parsed
write( value, ...) or appends to document opened with open( ). Returns nothing.
Example: document.write( value, ...)

Identical to write( ), except that it appends a newline character to the output.


writeln( value, ...) Returns nothing.
Example: document.writeln( value, ...)

 The W3C DOM: This document object model allows access and modification of all document content and
is standardized by the World Wide Web Consortium (W3C). This model is supported by almost all the
modern browsers.
Document Properties in W3C DOM:
This model supports all the properties available in Legacy DOM. Additionally, here is the list of document
properties which can be accessed using W3C DOM:

Property Description & Example

A reference to the Element object that represents the <body> tag of this document.
Body
Example: document.body

Its Read-only property and represents the window in which the document is displayed.
defaultView
Example: document.defaultView

A read-only reference to the <html> tag of the document.


documentElement
Example: document.documentElement8/31/2008

Its Read-only property and represents the DOMImplementation object that represents the
implementation implementation that created this document.
Example: document.implementation

Document Methods in W3C DOM:


This model supports all the methods available in Legacy DOM. Additionally, here is the list of methods supported
by W3C DOM:

Property Description & Example

Returns a newly-created Attr node with the specified


createAttribute( name) name.
Example: document.createAttribute( name)

Creates and returns a new Comment node containing the


createComment( text) specified text.
Example: document.createComment( text)

Creates and returns an empty DocumentFragment node.


createDocumentFragment( )
Example: document.createDocumentFragment( )

Creates and returns a new Element node with the


createElement( tagName) specified tag name.
Example: document.createElement( tagName)

Creates and returns a new Text node that contains the


createTextNode( text)
specified text.
Example: document.createTextNode( text)

Returns the Element of this document that has the


specified value for its id attribute, or null if no such
getElementById( id)
Element exists in the document.
Example: document.getElementById( id)

Returns an array of nodes of all elements in the


document that have a specified value for their name
getElementsByName( name) attribute. If no such elements are found, returns a zero-
length array.
Example: document.getElementsByName( name)

Returns an array of all Element nodes in this document


that have the specified tag name. The Element nodes
getElementsByTagName( tagname) appear in the returned array in the same order they
appear in the document source.
Example: document.getElementsByTagName( tagname)

Creates and returns a copy of a node from some other


document that is suitable for insertion into this
document. If the deep argument is true, it recursively
importNode( importedNode, deep)
copies the children of the node too. Supported in DOM
Version 2
Example: document.importNode( importedNode, deep)

 The IE4 DOM: This document object model was introduced in Version 4 of Microsoft's Internet Explorer
browser. IE 5 and later versions include support for most basic W3C DOM features.
Document Properties in IE 4 DOM:
The following non-standard (and non-portable) properties are defined by Internet Explorer 4 and later versions.

Property Description & Example

A read-only property that refers to the input element that is currently active (i.e., has the input
activeElement focus).
Example: document.activeElement

An array of all Element objects within the document. This array may be indexed numerically
all[ ] to access elements in source order, or it may be indexed by element id or name.
Example: document.all[ ]

The character set of the document.


Charset
Example: document.charset

An array that contains the HTML elements that are direct children of the document. Note that
this is different than the all[ ] array that contains all elements in the document, regardless of
children[ ]
their position in the containment hierarchy.
Example: document.children[ ]

The default character set of the document.


defaultCharset
Example: document.defaultCharset

expando This property, if set to false, prevents client-side objects from being expanded.
Example: document.expando

The window that contains the document.


parentWindow
Example: document.parentWindow

Specifies the loading status of a document. It has one of the following four string values:
readyState
Example: document.readyState

The document has not started loading.


uninitialized
Example: document.uninitialized

The document is loading.


loading
Example: document.loading

The document has loaded sufficiently for the user to interact with it.
interactive
Example: document.interactive

The document is completely loaded.


complete
Example: document.complete

Document Methods in IE4 DOM:


This model supports all the methods available in Legacy DOM. Additionally, here is the list of methods supported
by IE4 DOM:

Property Description & Example

Returns the Element located at a specified point.


elementFromPoint(x,y)
Example: document.elementFromPoint(x,y)

DOM compatibility
If you want to write a script that uses the W3C DOM when it is available, and otherwise uses the IE 4 DOM if it is
available, you can use a capability-testing approach that first checks for the existence of a method or property to
determine whether the browser has the capability you desire. For example:

if (document.getElementById) {

// If the W3C method exists, use it

else if (document.all) {

// If the all[] array exists, use it

else {

// Otherwise use the legacy DOM

2. Explain (i) Function within functions in JavaScript


A function is a group of reusable code which can be called anywhere in your programme. This eliminates the need
of writing same code again and again. This will help programmers to write modular code. You can divide your big
programme in a number of small and manageable functions.
Like any other advance programming language, JavaScript also supports all the features necessary to write modular
code using functions.
You must have seen functions like alert() and write() in previous chapters. We are using these function again and
again but they have been written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section will explain you how to write your own
functions in JavaScript.

Function Definition:
Before we use a function we need to define that function. The most common way to define a function in JavaScript
is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty),
and a statement block surrounded by curly braces. The basic syntax is shown here:

<script type="text/javascript">
<!--
function functionname(parameter-list)
{
statements
}
//-->
</script>

Example:
A simple function that takes no parameters called sayHello is defined here:

<script type="text/javascript">
<!--
function sayHello()
{
alert("Hello there");
}
//-->
</script>

Calling a Function:
To invoke a function somewhere later in the script, you would simple need to write the name of that function as
follows:

<script type="text/javascript">
<!--
sayHello();
//-->
</script>

Function Parameters:
Till now we have seen function without a parameters. But there is a facility to pass different parameters while
calling a function. These passed parameters can be captured inside the function and any manipulation can be done
over those parameters.
A function can take multiple parameters separated by comma.
Example:
Let us do a bit modification in our sayHello function. This time it will take two parameters:
<script type="text/javascript">
<!--
function sayHello(name, age)
{
alert( name + " is " + age + " years old.");
}
//-->
</script>

Note: We are using + operator to concatenate string and number all together. JavaScript does not mind in adding
numbers into strings.
Now we can call this function as follows:

<script type="text/javascript">
<!--
sayHello('Zara', 7 );
//-->
</script>

(ii) History object used in JavaScript


In this JavaScript ,history object properties and methods, length, current, next, previous properties, back(), forward()
and go() methods along with syntax and examples.

The history property has the return value as history object, which is an array of history items having details of the
URL‟s visited from within that window. Also, note that the History object is a JavaScript object and not an HTML
DOM object An example to understand the length property of history object:

<html>
<body>
<script type="text/javascript">
var ex = history.length;
document.write("The number of pages visited
before this page is" +ex+ " pages!!!.")
</script>
</body>
</html>

An example to understand the back method of history object:

<html>
<head>
<script type="text/javascript">
function funback()
{
window.history.back()
}
</script>
</head>

<body>
<input type="button" value="Press the Button to go
to Previous Page!!!" onclick="funback()" />
</body>
</html>

An example to understand the forward method of history object in brief:

<html>
<head>
<script type="text/javascript">
function funfor()
{
window.history.forward()
}
</script>
</head>

<body>
<input type="button" value="Press the Button to go
to Next Page!!!" onclick="funfor()" />
</body>
</html>

3. “IS JavaScript as an object model “Justify it.


Same in question 1.
4. Explain regular expressions in Java Script with some examples.
Regular Expression allows for straightforward searching, substitution, extraction and concatenation of strings. It is
series of characters that serves as a pattern-matching template.
Method uses search(), replace(), match(), split()
Syntax: match operator (m/pattern/ or /pattern/)

Regular expressions in JavaScript are used through the RegExp object, which is a native JavaScript object, as are
String, Array, and so on. There are two ways of creating a new RegExp object. The easier is with a regular
expression literal, such as the following:
var myRegExp = /\b‟|‟\b/;

The forward slashes (/) mark the start and end of the regular expression. This is a special syntax that tells JavaScript
that the code is a regular expression, much as quote marks define a string‟s start and end.

Alternatively, you could use the RegExp object‟s constructor function RegExp() and type the following:

var myRegExp = new RegExp(“\\b‟|‟\\b”);

Regular Expression: Special Characters


Symbol Matches
^ Beginning of line
$ End of line
\b Word boundary
\B Nonword boundary
\w word (alphanumeric character)
\W Nonword character
\d Digit(0 to 9)
\D Nondigit
\s Whitespace
\S Nonwhite space
\n Newline
\t Tab

Repetition Characters

Quantifier Matches Example


{n} Exactly n times x{2} matches xx
{m, n} Between m and n time inclusive x{2,4} matches xx, xxx,
and xxxx
{n, } n or more times x{2,} matches xx, xxx,
xxxx, xxxxx, and so on
+ One or more times(same as {1,}) x + matches x, xx, xxx,
xxxx, xxxxx, and so on
? one or zero times (same as {0,1}) x? matches nothing or x
Some Modifying characters

Attribute Character Purpose


g Performs a global search, finds and returns all matches, not
just the first one found
i Ignores the case of the search string(case insensitive)
m The string is evaluated as if it had multiple lines of
text. (newline characters are not ignored).
s Ignores a newline character and treats it as whitespace.
The text is seen as a single line.
x All whitespace characters in the regular expression are
ignored. Searching the string

Eg:
Text String: ‘Now is is the time’
Case1: string „Now‟ was found
RegExp = /Now/

Case2: String „Now‟ was found at the beginning of the line


RegExp = /^Now/

Case3: Word found ending in „ow‟


RegExp = / \b (\w+ ow) \b/x

Case4: Repeated words found:


RegExp= / \b ( \w+ ) \s (\1) \b/x

Case5: words beginning with „t‟ found: matches


RegExp= / \b (t \w+ ) \b /gx

Replace() Method

<html>
<head>
< <title>Regular Expression</title>
</head>
<body>
<script language = "JavaScript" type = "text/JavaScript">
var myString = "JavaScript, VBScript and Perl";
var myRegExp = /\b(VB)?(Java)?Script\b/gi;
myString = myString.replace(myRegExp, "xxxx");
alert(myString);
</script>
</body>
</html>

O/P:

Match() Method

<html>
<head>

<title>Match method</title>
</head>
<body>

<script language="JavaScript" >


var myString = "The years were 1999, 2000 and 2001";
var myRegExp = /\b\d{4}\b/g;
var resultsArray = myString.match(myRegExp);
if (resultsArray)
{
var indexCounter;
for (indexCounter = 0; indexCounter < resultsArray.length; indexCounter++)
{
alert(resultsArray[indexCounter]);
}
}

</script>
</body>

</html>

O/P:
First dialog box: 1999
second dialog box: 2000
third dialog box: 2001

Search() Method
<html >
<head>
<title>Search Method</title>
</head>
<body>
<script language="JavaScript" type = "text/JavaScript">
var myString = "Beginning JavaScript, Beginning Java 2, Professional JavaScript";
var myRegExp = /\b Professional\b /i ;
alert (myString.search(myRegExp));
</script>
</body>
</html>
O/P:
First dialog box: 40
Split() Method
<html>
<head>
<title>split Method</title>
</head>
<body>
<script language = "JavaScript" type = "text/JavaScript">
var myListString = "apple, 0.99, banana, 0.50, peach, 0.25, orange, 0.75";
var theRegExp = /[^a-z]+/i;
var myFruitArray = myListString.split (theRegExp);
document.write (myFruitArray.join ("<br>"));
</script>
</body>
</html>
O/P:
apple
banana
peach
orange

5. (a)Discuss javascript Array object in detail.


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

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

var car1="Saab";
var car2="Volvo";
var car3="BMW";

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

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.

Create an Array

An array can be created in three ways.

The following code creates an Array object called myCars:

1: Regular:

var myCars=new Array();


myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

2: Condensed:

var myCars=new Array("Saab","Volvo","BMW");

3: Literal:

var myCars=["Saab","Volvo","BMW"];
(b)Discuss about Javascript debugging.
6. i) Write a simple program in javascript to print multiple line of text in a web page with a program
with single statement
Ans. <html>
<head>
<title>Printing a Line with Multiple Statements</title>

<script type = "text/javascript">


<!--
document.write( "<h1 style = \"color: magenta\">" );
document.write( "Welcome to JavaScript " +
"Programming!</h1>" );
// -->
</script>
</head><body></body>
</html>
Output:

Welcome to JavaScript Programming!

(ii) Write a java script program for alert dialog box displaying multiple lines.
Ans. <html>
<head><title>Printing Multiple Lines in a Dialog Box</title>

<script type = "text/javascript">


<!--
window.alert( "Welcome to\nJavaScript\nProgramming!" );
// -->
</script>

</head>

<body>
<p>Click Refresh (or Reload) to run this script again.</p>
</body>
</html>

Output:

Then ok is clicked on
Click Refresh (or Reload) to run this script again.
.(ii) Write a java script program for alert dialog box displaying multiple lines.
Ans.
<html>
<head>
<title>Class Average Program</title>

<script type = "text/javascript">


<!--
var total, // sum of grades
gradeCounter, // number of grades entered
gradeValue, // grade value
average, // average of all grades
grade; // grade typed by user

// Initialization Phase
total = 0; // clear total
gradeCounter = 1; // prepare to loop
// Processing Phase
while ( gradeCounter <= 10 ) { // loop 10 times

// prompt for input and read grade from user


grade = window.prompt( "Enter integer grade:", "0" );

// convert grade from a String to an integer


gradeValue = parseInt( grade );

// add gradeValue to total


total = total + gradeValue;

// add 1 to gradeCounter
gradeCounter = gradeCounter + 1;
}

// Termination Phase
average = total / 10; // calculate the average

// display average of exam grades


document.writeln(
"<h1>Class average is " + average + "</h1>" );
// -->
</script>

</head>
<body>
<p>Click Refresh (or Reload) to run the script again</p>
</body>
</html>
Output:
The entered the 10 number in prompt window

Class average is 4.7

Click Refresh (or Reload) to run the script again

7. i) Write a program in java script to calculate a class average using sentinel controlled repetition
<html>
<head>
<title>Switching between XHTML List Formats</title>

<script type = "text/javascript">


<!--
var choice, // user’s choice
startTag, // starting list item tag
endTag, // ending list item tag
validInput = true, // indicates if input is valid
listType; // list type as a string

choice = window.prompt( "Select a list style:\n" +


"1 (bullet), 2 (numbered), 3 (lettered)", "1" );

switch ( choice ) {
case "1":
startTag = "<ul>";
endTag = "</ul>";
listType = "<h1>Bullet List</h1>";
break;
case "2":
startTag = "<ol>";
endTag = "</ol>";
listType = "<h1>Ordered List: Numbered</h1>";
break;
case "3":
startTag = "<ol type = \"A\">";
endTag = "</ol>";
listType = "<h1>Ordered List: Lettered</h1>";
break;
default:
validInput = false;
}

if ( validInput == true ) {
document.writeln( listType + startTag );

for ( var i = 1; i <= 3; ++i )


document.writeln( "<li>List item " + i + "</li>" );

document.writeln( endTag );
}
else
document.writeln( "Invalid choice: " + choice );
// -->
</script>

</head>
<body>
<p>Click Refresh (or Reload) to run the script again</p>
</body>
</html>

Output:

Ordered List: Numbered

1. List item 1
2. List item 2
3. List item 3
Click Refresh (or Reload) to run the script again
. (ii) Write a program in java script to switch between XHTML list formats using switch case
statement.
8. (i) Write a program in java script to convert number bases
Ans. <!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to display the formatted number.</p>

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


<script>
function myFunction()
{
var num = 15;
var a = num.toString();
var b = num.toString(2);
var c = num.toString(8);
var d = num.toString(16);

var n=a + "<br>" + b + "<br>" + c + "<br>" + d;

var x = document.getElementById("demo");
x.innerHTML=n
}
</script>

</body>
</html>
Output:
15
1111
17
f

9. .(ii) Write a program in java script to find maximum of 3 numbers using standard mat function.
<html>
<head>
<title>Finding the Maximum of Three Values</title>

<script type = "text/javascript">


<!--
var input1 =
window.prompt( "Enter first number", "0" );
var input2 =
window.prompt( "Enter second number", "0" );
var input3 =
window.prompt( "Enter third number", "0" );

var value1 = parseFloat( input1 );


var value2 = parseFloat( input2 );
var value3 = parseFloat( input3 );

var maxValue = maximum( value1, value2, value3 );

document.writeln( "First number: " + value1 +


"<br />Second number: " + value2 +
"<br />Third number: " + value3 +
"<br />Maximum is: " + maxValue );

// maximum method definition (called from line 25)


function maximum( x, y, z )
{
return Math.max( x, Math.max( y, z ) );
}
// -->
</script>
</head>
<body>
<p>Click Refresh (or Reload) to run the script again</p>
</body>
</html>
Output:
First number: 8
Second number: 4
Third number: 6
Maximum is: 8

Click Refresh (or Reload) to run the script again

10. (i) Write a program in java script to calculate factorial using recursive function.
<html >
<head>
<title>Recursive Factorial Function</title>
11.
12. <script type = "text/javascript">
13. <!--
14. document.writeln( "<h1>Factorials of 1 to 10</h1>" );
15. document.writeln(
16. "<table border = '1' width = '100%'>" );
17.
18. for ( var i = 0; i <= 10; i++ )
19. document.writeln( "<tr><td>" + i + "!</td><td>" +
20. factorial( i ) + "</td></tr>" );
21.
22. document.writeln( "</table>" );
23.
24. // Recursive definition of function factorial
25. function factorial( number )
26. {
27. if ( number <= 1 ) // base case
28. return 1;
29. else
30. return number * factorial( number - 1 );
31. }
32. // -->
33. </script>
34. </head><body></body>
35. </html>
36. Output:
37. Factorials of 1 to 10

0! 1
1! 1
2! 2
3! 6
4! 24
5! 120
6! 720
7! 5040
8! 40320
9! 362880
10! 3628800
(ii)Write program in java script to sort an array.
<html>
<head>
<title>Sorting an Array with Array Method sort</title>

<script type = "text/javascript">


<!--
function start()
{
var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ];

document.writeln( "<h1>Sorting an Array</h1>" );


outputArray( "Data items in original order: ", a );
a.sort( compareIntegers ); // sort the array
outputArray( "Data items in ascending order: ", a );
}

// outputs "header" followed by the contents of "theArray"


function outputArray( header, theArray )
{
document.writeln( "<p>" + header +
theArray.join( " " ) + "</p>" );
}

// comparison function for use with sort


function compareIntegers( value1, value2 )
{
return parseInt( value1 ) - parseInt( value2 );
}
// -->
</script>

</head><body onload = "start()"></body>


</html>
Output:

Sorting an Array

Data items in original order: 10 1 9 2 8 3 7 4 6 5


Data items in ascending order: 1 2 3 4 5 6 7 8 9 10

10.Develop a welcome page using various JavaScript concepts.

Das könnte Ihnen auch gefallen