Sie sind auf Seite 1von 15

Internet, Intranet & Web Page Development

JavaScript Lab Sheet 1

Lab Sheet : JavaScript


Basics
Example 1
Using the SCRIPT tag
<HTML>
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
document.write("Hello World");
</SCRIPT>
</HEAD>
</HTML>
Example 2
Using variables
<HTML>
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
var secs_per_min = 60;
var mins_per_hour = 60;
var hours_per_day = 24;
var days_per_year = 365;
var secs_per_day = secs_per_min * mins_per_hour * hours_per_day;
var secs_per_year = secs_per_day * days_per_year;
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE = "JavaScript">
document.write("<B>There are ");
document.write(secs_per_year);
document.write(" seconds per year.</B>");
</SCRIPT>
</BODY>
</HTML>
Example 3
Using strings
<HTML>
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
var a = "This sentence ";
var b = "is continued over ";
var c = "three variables.";
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE = "JavaScript">
var sentence = a + b + c;
document.write(sentence);
</SCRIPT>
</BODY></HTML>

Ranjan Parekh
School of Education Technology, Jadavpur University, Calcutta, India
www.geocities.com/rparekhju/

Internet, Intranet & Web Page Development


JavaScript Lab Sheet 1
Example 4
Modifying the appearance of strings
<HTML>
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
var a = "This sentence ";
var italics_a = a.italics();
var b = "is continued over ";
var upper_b = b.toUpperCase();
var c = "three variables.";
var red_c = c.fontcolor("red");
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE = "JavaScript">
var sentence = italics_a + upper_b + red_c;
document.write(sentence);
</SCRIPT>
</BODY>
</HTML>
Example 5
Using HTML tags within strings
<HTML>
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
var a = "This sentence ";
var italics_a = a.italics();
var b = "is continued over ";
var upper_b = b.toUpperCase();
var c = "three variables.";
var red_c = c.fontcolor("red");
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE = "JavaScript">
var sentence = italics_a + "<BR>" + upper_b + "<HR>" + red_c;
document.write(sentence);
</SCRIPT>
</BODY>
</HTML>
Example 6
Taking user input
<HTML>
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
var message = prompt("What is your name?","");
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>

Ranjan Parekh
School of Education Technology, Jadavpur University, Calcutta, India
www.geocities.com/rparekhju/

Internet, Intranet & Web Page Development


JavaScript Lab Sheet 1
Example 7
Working with the user input
<HTML>
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
var message = prompt("What is your name?","");
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE = "JavaScript">
document.write("<B>Hello, " + message.italics() + " how do you do?</B>");
</SCRIPT>
</BODY>
</HTML>
Example 8
If-then-else branching
<HTML>
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
var message = prompt("Is it past 12 noon yet?","Type yes or no");
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE = "JavaScript">
if (message == "yes")
{
document.write("Good Afternoon!");
}
else
{
document.write("Good Morning!");
}
</SCRIPT>
</BODY>
</HTML>
Example 9
Using the while loop to generate a sequence of numbers
<HTML>
<BODY>
<SCRIPT LANGUAGE=JavaScript >
var n=0;
while (n <= 10)
{
document.write(n + "<BR>")
n=n+1;
}
</SCRIPT>
</BODY>
</HTML>

Example 10
Using a for loop to generate a series of characters
<HTML>
<BODY>
<SCRIPT LANGUAGE="JavaScript">

Ranjan Parekh
School of Education Technology, Jadavpur University, Calcutta, India
www.geocities.com/rparekhju/

Internet, Intranet & Web Page Development


JavaScript Lab Sheet 1
var width = prompt("How many x's would you like? (1-100 is good)","5");
var a_line="";
for (loop=0; loop < width; loop++)
{
a_line = a_line + "x";
}
alert(a_line);
</SCRIPT>
</BODY>
</HTML>

Example 11
Using logical operators
<HTML>
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
var marks = prompt("Enter percentage marks");
if ((marks <= 80 ) && (marks > 70))
{
document.write("Grade B");
}
var temp = prompt("Enter temperature below", "in degrees centigrade");
if ((temp < 0) || (temp > 100))
{
document.write("<BR>No liquid water.");
}
else
{
document.write("<BR>Liquid water exists.");
}
</SCRIPT>
</HEAD>
</HTML>
Example 12
Displaying alerts
<HTML>
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
alert("This is an example of an alert!");
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
Example 13
Displaying alerts by clicking a hyperlink
<HTML>
<HEAD>
</HEAD>
<BODY>
<A HREF = "#" onClick = "alert('Thank you! Do it again');">
Click on me</A>
</BODY>
</HTML>

Ranjan Parekh
School of Education Technology, Jadavpur University, Calcutta, India
www.geocities.com/rparekhju/

Internet, Intranet & Web Page Development


JavaScript Lab Sheet 1

Example 14
Displaying alerts by mouse over
<HTML>
<HEAD>
</HEAD>
<BODY>
<A HREF = "#" onMouseOver = "alert('Thank you! Do it again');">
Move the mouse pointer over me</A>
</BODY>
</HTML>
Example 15
Preventing auto re-loading of a page
<HTML>
<BODY>
1. This page has several lines. This page has several lines.
<br>
2. This page has several lines. This page has several lines.
<br>
3. This page has several lines. This page has several lines.
<br>
4. This page has several lines. This page has several lines.
<br>
5. This page has several lines. This page has several lines.
<br>
6. This page has several lines. This page has several lines.
<br>
7. This page has several lines. This page has several lines.
<br>
8. This page has several lines. This page has several lines.
<br>
9. This page has several lines. This page has several lines.
<br>
10. This page has several lines. This page has several lines. <br>
11. This page has several lines. This page has several lines. <br>
12. This page has several lines. This page has several lines. <br>
13. This page has several lines. This page has several lines. <br>
14. This page has several lines. This page has several lines. <br>
15. This page has several lines. This page has several lines. <br>
16. This page has several lines. This page has several lines. <br>
17. This page has several lines. This page has several lines. <br>
18. This page has several lines. This page has several lines. <br>
19. This page has several lines. This page has several lines. <br>
20. This page has several lines. This page has several lines. <br>
21. This page has several lines. This page has several lines. <br>
22. This page has several lines. This page has several lines. <br>
23. This page has several lines. This page has several lines. <br>
24. This page has several lines. This page has several lines. <br>
25. This page has several lines. This page has several lines. <br>
26. This page has several lines. This page has several lines. <br>
27. This page has several lines. This page has several lines. <br>
28. This page has several lines. This page has several lines. <br>
29. This page has several lines. This page has several lines. <br>
30. This page has several lines. This page has several lines. <br>
<p>
<A HREF = "#" onClick = "alert('Thank you! Do it again'); return false">Click on me(without
reloading)</A>
</BODY>
</HTML>
Example 16
Using buttons to display alerts
<HTML>
<BODY>
<INPUT TYPE = "button" VALUE = "Click to display an alert" onClick = "alert('This is an alert');">
</BODY>
</HTML>

Ranjan Parekh
School of Education Technology, Jadavpur University, Calcutta, India
www.geocities.com/rparekhju/

Internet, Intranet & Web Page Development


JavaScript Lab Sheet 1
Example 17
Image swapping
<HTML>
<HEAD>
</HEAD>
<BODY>
<IMG SRC="mouse.gif" NAME="the_image"><BR><BR>
<A HREF="#" onMouseOver="document.the_image.src='gears.gif';">Change</A>
</BODY>
</HTML>
Example 18
Creating new windows
<HTML>
<HEAD>
</HEAD>
<BODY>
<A HREF="#" onClick="window.open('17a.htm','window1');">First Window</A> &nbsp;
<A HREF="#" onClick="window.open('17b.htm','window2');">Second Window</A> &nbsp;
<A HREF="#" onClick="window.open('17c.htm','window2');">Third Window</A> &nbsp;
</BODY>
</HTML>

Ranjan Parekh
School of Education Technology, Jadavpur University, Calcutta, India
www.geocities.com/rparekhju/

Internet, Intranet & Web Page Development


JavaScript Lab Sheet 1

Core JavaScript
Array
An object representing an array. The following syntax is used to create an Array object :
new Array()
new Array(array-length)
new Array(element0, element1, , elementN)
Properties
length

Denotes the number of elements in the array

Methods
join(separator)
pop()
push()
reverse()
shift()
slice(begin,numb)
unshift()
sort(compareFunction)

Joins all elements of an array into a string.


Removes the last element from an array and returns that element. Changes the
length of an array.
Adds one or more elements to the end of an array and returns the last element
added.
Reverses the order of the elements of an array.
Removes the first element of an array and returns that element. Changes
length of array.
Extracts a section of an array and returns a new array.
Adds one or more elements to the beginning of an array and returns the new
length of the array.
Sorts the elements of an array either lexicographically (dictionary order) or by
a specified function.

Example 19
Creating and printing arrays
<SCRIPT LANGUAGE="JavaScript">
var elements = new Array("Wind", "Rain", "Fire");
document.write(elements + "<P>");
var myArray = new Array();
myArray[0] = "disk";
myArray[5] = "CPU";
document.write(myArray + "<P>");
var numbers = new Array(3);
for (i=0; i<5; i++)
numbers[i] = i;
document.write(numbers + "<P>");
var numbers = new Array(10);
for (i=0; i<numbers.length; i++)
numbers[i] = i;
document.write(numbers + "<P>");
</SCRIPT>
Example 20
Manipulating array elements 1
<SCRIPT LANGUAGE="JavaScript">
var myArray = new Array("Wind", "Rain", "Fire");
document.write(myArray.join("+") + "<BR>");
document.write(myArray.join(", ") + "<P>");
document.write("Array before pop: " + myArray + "<BR>");
popped = myArray.pop();
document.write("Array after pop : " + myArray + "<BR>");

Ranjan Parekh
School of Education Technology, Jadavpur University, Calcutta, India
www.geocities.com/rparekhju/

Internet, Intranet & Web Page Development


JavaScript Lab Sheet 1
document.write("Popped this element : " + popped + "<P>");
pushed = myArray.push("Space");
document.write("Array after push: " + myArray + "<BR>");
</SCRIPT>
Example 21
Manipulating array elements 2
<SCRIPT LANGUAGE="JavaScript">
var myArray = new Array("Wind", "Rain", "Fire");
document.write("Array before reverse: " + myArray + "<BR>");
myArray.reverse();
document.write("Array after reverse: " + myArray + "<P>");
myArray = new Array("Wind", "Rain", "Fire");
document.write("Array before shift: " + myArray + "<BR>");
shifted = myArray.shift();
document.write("Array after shift : " + myArray + "<BR>");
document.write("Removed this element : " + shifted + "<P>");
myArray = new Array("Wind", "Rain", "Fire", "Space");
document.write("Array myArray: " + myArray + "<BR>");
var newArray = myArray.slice(0,2);
document.write("Array newArray: " + newArray + "<P>");
myArray = new Array("Wind", "Rain", "Fire");
document.write("Array before unshift: " + myArray + "<BR>");
unshifted = myArray.unshift("Space");
document.write("Array after unshift: " + myArray + "<BR.");
</SCRIPT>
Example 22
Sorting an array
<SCRIPT LANGUAGE="JavaScript">
stringArray = new Array("Blue", "Humpback", "Beluga");
mixedNumericArray = new Array(80, 9, 700, 40, 1, 5, 200);
function compareNumbers(a, b){return (a-b)};
document.write("<B>StringArray :</B> " + stringArray.join() + "<BR>");
document.write("<B>Sorted : </B> " + stringArray.sort() + "<P>");
document.write("<B>MixedNumericArray : </B>" + mixedNumericArray.join() + "<BR>");
document.write("<B>Sorted without compare function : </B>"+ mixedNumericArray.sort() +
"<BR>");
document.write("<B>Sorted with compareNumbers : </B>" +
mixedNumericArray.sort(compareNumbers) + "<BR>");
</SCRIPT>

Boolean
An object representing Boolean value. The following syntax is used for creating a Boolean object :
new Boolean(value)
where value is the initial value of the Boolean object. If the value is omitted or 0 or null or false or the
empty string , the object has an initial value of false. All other values create an object with an initial
value of true.

Example 23
Manipulating Boolean objects
<SCRIPT LANGUAGE="JavaScript">
bNoParam = new Boolean();
bZero = new Boolean(0);
bNull = new Boolean(null);
bEmptyString = new Boolean('');

Ranjan Parekh
School of Education Technology, Jadavpur University, Calcutta, India
www.geocities.com/rparekhju/

Internet, Intranet & Web Page Development


JavaScript Lab Sheet 1
bFalse = new Boolean(false);
bTrue = new Boolean(true);
btrueString = new Boolean('true');
bfalseString = new Boolean('false');
bapple = new Boolean('apple');
document.write("<B>Value
document.write("<B>Value
document.write("<B>Value
document.write("<B>Value
document.write("<B>Value
document.write("<B>Value
document.write("<B>Value
document.write("<B>Value
document.write("<B>Value
</SCRIPT>

of
of
of
of
of
of
of
of
of

Boolean() is : </B>" + bNoParam + "<BR>");


Boolean(0) is : </B>" + bZero + "<BR>");
Boolean(null) is : </B>" + bNull + "<BR>");
Boolean('') is : </B>" + bEmptyString + "<BR>");
Boolean(false) is : </B>" + bFalse + "<BR>");
Boolean(true) is : </B>" + bTrue + "<BR>");
Boolean('true') is : </B>" + btrueString + "<BR>");
Boolean('false') is : </B>" + bfalseString + "<BR>");
Boolean('apple') is : </B>" + bapple + "<BR>");

Date
An object representing dates and times. The following syntax is used for creating a Date object :
new Date();
new Date(date-string);
new Date(milliseconds);
new Date(yr mo day hr min sec ms);
Here date-string can be : 12 January 2003
Milliseconds in the number of ms since Jan 1, 1970, 00:00:00
Here mo ranges from 0 (January) to 11(December).
JavaScript stores dates internally as numbers representing milliseconds since January 1, 1970 00:00:00.
Dates prior to this are not allowed.
Methods
getDate, setDate
getDay, setDay
getHours, setHours
getMinutes, setMinutes
getMonth, setMonth
getSeconds, setSeconds
getYear, setYear
getTime, setTime
toGMTString

Returns, sets the current date (1 - 31).


Returns, sets the current day of the week (0 for Sunday 6 for Saturday)
Returns, sets the current hour of the day (0 23).
Returns, sets the current minute of the hour (0 59)
Returns, sets the current month of the year (0 11)
Returns, sets the current seconds of the minute (0 59)
Returns, sets the current year of the century (0 99)
Returns, sets the total number of milliseconds since January 1, 1970 00:00:00
Converts current date to Universal Time Coordinates (Greenwich time)

Example 24
Manipulating Date objects
<SCRIPT LANGUAGE="JavaScript">
Xmas2000 = new Date("25
document.write("<B>Value
document.write("<B>Value
document.write("<B>Value
document.write("<B>Value
document.write("<B>Value
document.write("<B>Value
document.write("<B>Value
document.write("<B>Value
document.write("<B>Value
document.write("<B>Value
</SCRIPT>

December 2000 23:15:00")


of Xmas2000 is : </B>" + Xmas2000 + "<BR>");
of toGMTString is : </B>" + Xmas2000.toGMTString() + "<BR>");
of getTime is : </B>" + Xmas2000.getTime() + "<BR>");
of getDate is : </B>" + Xmas2000.getDate() + "<BR>");
of getDay is : </B>" + Xmas2000.getDay() + "<BR>");
of getHours is : </B>" + Xmas2000.getHours() + "<BR>");
of getMinutes is : </B>" + Xmas2000.getMinutes() + "<BR>");
of getMonth is : </B>" + Xmas2000.getMonth() + "<BR>");
of getSeconds is : </B>" + Xmas2000.getSeconds() + "<BR>");
of getYear is : </B>" + Xmas2000.getYear() + "<BR>");

Ranjan Parekh
School of Education Technology, Jadavpur University, Calcutta, India
www.geocities.com/rparekhju/

Internet, Intranet & Web Page Development


JavaScript Lab Sheet 1

Math
An object that has properties and methods for mathematical constants and functions. To use a Math
object, use the following syntax:
Math.propertyname
Math.methodname
Properties
E
LN10
LN2
LOG10E
LOG2E
PI
SQRT1_2
SQRT2

Eulers constant and base of natural logarithm. Equal to 2.718 approximately.


The natural logarithm of 10, approximately 2.302.
The natural logarithm of 2, approximately 0.693.
The base 10 logarithm of E (approximately 0.434).
The base 2 logarithm of E (approximately 1.442).
The ratio of circumference to diameter of a circle. Equal to 3.1415 approx.
The square root of 1/2. Equal to 0.707 approx.
The square root of 2. Equal to 1.414 approximately.

Methods
abs(x)
ceil(x)
sin(x), cos(x), tan(x)
exp(x)
floor(x)
max(x,y)
min(x,y)
pow(x,y)
random()
sqrt(x)

Returns absolute value of a number


Returns the smallest integer greater than or equal to a number.
Returns the sine, cosine and tangent of a number
Returns Ex, where x is the argument, and E is Euler's constant, the base of the
natural logarithms
Returns the largest integer less than or equal to a number.
Returns the larger of two numbers.
Returns the smaller of two numbers
Returns base to the exponent power, that is, baseexponent
Returns a random number between 0 and 1
Returns the square root of a number.

Example 25
Manipulating Math objects 1
<SCRIPT LANGUAGE="JavaScript">
document.write("<b>Value of e: </b>" + Math.E + "<BR>")
document.write("<b>Value of pi: </b>" + Math.PI + "<BR>")
document.write("<b>Value of square root 2: </b>" + Math.SQRT2 + "<BR>")
</SCRIPT>
Example 26
Manipulating Math objects 2
<SCRIPT LANGUAGE="JavaScript">
document.write(Math.abs(-2.5) + "<BR>")
document.write(Math.ceil(-2.5) + "<BR>")
document.write(Math.floor(-2.5) + "<BR>")
document.write(Math.pow(2,5) + "<BR>")
document.write(Math.sin(Math.PI/2) + "<BR>")
</SCRIPT>

Ranjan Parekh
School of Education Technology, Jadavpur University, Calcutta, India
www.geocities.com/rparekhju/

10

Internet, Intranet & Web Page Development


JavaScript Lab Sheet 1

Number
An object representing a number. The following syntax is used for creating a Number object :
new Number(value)
where value is a numerical value.
Properties
MAX_VALUE
MIN_VALUE
POSITIVE_INFINITY
NEGATIVE_INFINITY
NaN

The maximum numeric value representable in JavaScript. Approximately equal


to 1.79e+308
The smallest positive numeric value representable in JavaScript. Approximately
equal to 5e-324
Special numeric value representing Infinity
Special numeric value representing Infinity.
Not A Number. Always unequal to any number including itself.

Methods
toString(radix)

Returns a string representation of the specified object.


Here radix is an optional integer between 2 and 16 specifying the base to use
for representing the value.

Example 27
Manipulating Number objects 1
<SCRIPT LANGUAGE="JavaScript">
var n = new Number(2);
document.write(Number.MAX_VALUE + "<BR>");
document.write(Number.MIN_VALUE + "<BR>");
document.write(n/0 + "<BR>");
document.write(Math.pow(-n,.5) + "<BR>");
</SCRIPT>
Example 28
Manipulating Number objects 2
<SCRIPT LANGUAGE="JavaScript">
var first_num = new Number(5487);
document.write("<b>In Decimal : </b>" + first_num + "<BR>");
document.write("<b>In Octal : </b>" + first_num.toString(8) + "<BR>");
document.write("<b>In Hex : </b>" + first_num.toString(16) + "<BR>");
document.write("<b>In Pental : </b>" + first_num.toString(5) + "<BR>");
document.write("<b>In Binary : </b>" + first_num.toString(2) + "<BR>");
</SCRIPT>

Ranjan Parekh
School of Education Technology, Jadavpur University, Calcutta, India
www.geocities.com/rparekhju/

11

Internet, Intranet & Web Page Development


JavaScript Lab Sheet 1

String
An object representing a string of characters. The following syntax is used for creating a String object :
new String(string)
where string is a string of characters
Properties
length

Returns the length of a string. For a null string length is 0.

Methods
big()
bold()
italics()
charAt(index)

Causes a string to be displayed in big font.


Causes a string to be displayed in bold.
Causes a string to be displayed in italics.
Returns the specified character from the string.
Here index is an integer from 0 to length-1, length pertaining to the length of
the string.
charCodeAt(index)
Returns the ASCII code of the character at the specified index.
Here index is an integer from 0 to length-1, length pertaining to the length of
the string.
concat(string)
Combines the text of two strings and returns a new string.
Here string is the string to concat with the current string.
fontcolor(color)
Causes a string to be displayed in a specified color.
Here color is a string expressing the color either as RGB hexadecimal triplets or
as a string literal.
fontsize(size)
Causes a string to be displayed in the specified font size. Here size is an integer
between 1 and 7.
fromCharCode(number) Returns a string corresponding to the specified ASCII code.
Here number represents ASCII code in decimal.
indexOf(string, spoint)
Returns the index within a string of the first occurrence of the specified value.
Here string is the string to search for, spoint specifies which character to begin
the search from.
link(URL)
Creates an HTML hypertext link that requests another URL.
match(/regexp/)
Used to match a regular expression against a string. For global match or case
insensitive match include flags g and i respectively. Here regexp is the regular
expression to match.
replace(regexp, newstr) Used to find a match between a regular expression and a string, and to replace
the matched substring regexp with the new substring newstr. For global match
or case insensitive match include flags g and i respectively.
slice(beginslice, endslice) Extracts a section of a string and returns a new string. Here beginslice is the
zero-based index at which to begin extraction, and endslice is the number of
characters from beginning where extraction should end.
small()
Causes a string to be displayed in a small font.
split(delimiter)
Returns an array whose elements are segments of the string.
sub(), super()
Causes a string to be displayed as a subscript or superscript.
toLowerCase()
Converts a string to lowercase.
toUpperCase()
Converts a string to uppercase.

Example 29
Manipulating String objects 1
<SCRIPT LANGUAGE="JavaScript">
var worldString=new String("Hello, world");
document.write("<P>" + worldString) ;
document.write("<P>" + worldString.big());
document.write("<P>" + worldString.big().big());
document.write("<P>The string length is " + worldString.length);
</SCRIPT>

Ranjan Parekh
School of Education Technology, Jadavpur University, Calcutta, India
www.geocities.com/rparekhju/

12

Internet, Intranet & Web Page Development


JavaScript Lab Sheet 1
Example 30
Manipulating String objects 2
<SCRIPT LANGUAGE="JavaScript">
var worldString= new String("Hello, world");
document.write("<P>" + worldString);
document.write("<P>" + worldString.bold());
document.write("<P>" + worldString.italics() + "<P>");
var anyString= new String("Brave new world");
document.write("The character at index 0 is " +
document.write("The character at index 1 is " +
document.write("The character at index 2 is " +
document.write("The character at index 3 is " +
document.write("The character at index 4 is " +

anyString.charAt(0)
anyString.charAt(1)
anyString.charAt(2)
anyString.charAt(3)
anyString.charAt(4)

+
+
+
+
+

"<BR>");
"<BR>");
"<BR>");
"<BR>");
"<P>");

document.write("ASCII code of character at index 0 is " + anyString.charCodeAt(0) + "<BR>");


document.write("ASCII code of character at index 1 is " + anyString.charCodeAt(1) + "<BR>")
document.write("ASCII code of character at index 2 is " + anyString.charCodeAt(2) + "<BR>")
</SCRIPT>
Example 31
Manipulating String objects 3
<SCRIPT LANGUAGE="JavaScript">
var str1= new String("The morning is upon us. ");
var str2= new String("The sun is bright.");
var str3=str1.concat(str2)
document.write(str3)
var worldString= new String("Hello, world")
document.write("<P>" + worldString.fontcolor("800000") + " is maroon in this line")
document.write("<BR>" + worldString.fontcolor("red") + " is red in this line")
document.write("<P>" + worldString.fontsize(7) + " is in size 7<P>")
document.write(String.fromCharCode(65, 66, 67))
</SCRIPT>

Ranjan Parekh
School of Education Technology, Jadavpur University, Calcutta, India
www.geocities.com/rparekhju/

13

Internet, Intranet & Web Page Development


JavaScript Lab Sheet 1
Example 32
Manipulating String objects 4
<SCRIPT LANGUAGE="JavaScript">
var anyString=new String("Brave new world")
document.write(anyString)
//Displays 1
document.write("<P>The index of the first r from the beginning is " + anyString.indexOf("r"))
//Displays 6
document.write("<P>The index of 'new' from the beginning is " + anyString.indexOf("new"))
//Displays 12
document.write("<P>The index of the second r from the beginning is " + anyString.indexOf("r",2))
var hotText="Netscape"
var URL="http://home.netscape.com"
document.write("<P>Click to return to " + hotText.link(URL) + "<P>")
str = new"abcDdcba";
newstr = str.match(/d/gi);
document.write(newstr);
re = /apples/gi;
str = "Apples are round, and apples are juicy.";
newstr=str.replace(re, "oranges");
document.write("<P>" + newstr)
</SCRIPT>
Example 33
Manipulating String objects 5
<SCRIPT LANGUAGE="JavaScript">
str1=new String("The morning is upon us.")
str2=str1.slice(3,5);
str3=str1.slice(3,-4);
document.write(str2);
document.write("<BR>" + str3);
var worldString=new String("Hello, world");
document.write("<P>" + worldString);
document.write("<BR>" + worldString.small());
document.write("<BR>" + worldString.small().small());
var superText=new String("superscript")
var subText= new String("subscript")
document.write("<P>This is what a " + superText.sup() + " looks like.")
document.write("<BR>This is what a " + subText.sub() + " looks like.")
var upperText= new String ("ALPHABET" )
document.write("<P>" + upperText.toLowerCase())
var lowerText= new String ("alphabet" )
document.write("<BR>" + lowerText.toUpperCase())
var numericstring = new String ("one+two+three+four-five+six");
var myArray = numericstring.split("+");
document.write("<P>" + myArray[3]);
</SCRIPT>

Ranjan Parekh
School of Education Technology, Jadavpur University, Calcutta, India
www.geocities.com/rparekhju/

14

Internet, Intranet & Web Page Development


JavaScript Lab Sheet 1

Problems
Problem 1
Write a JavaScript code to generate prompt dialog boxes one after one. The first prompt box should ask
the user to specify the first primary color by typing either R or G or B. The second prompt box should
likewise ask the user to specify the second primary color. Based on the user choices the program should
generate the message Your favourite color is x where x is the name of the secondary color formed from
the specified primary colors. The color of the message text should also be same as x.
Problem-2
Create a password protected Web page where the user is repeatedly asked to enter a password as long as
the correct password is not supplied.
Problem 3
Generate a grid of characters by asking the user to specify how wide and high the grid should be.
Problem 4
Write a JavaScript program to generate two prompt dialog boxes to the user. The first one should accept a
numerical value while the second one the name of a unit, either inch or cm. The program should
convert the value to the other unit and display the result in an alert box.
Problem 5
Write a JavaScript program to (a) accept a date from the user and display the name of the weekday (i.e.
Monday, Tuesday ... etc.) it corresponds to (b) Print the current date in the form mm/dd/yyyy.
Problem 6
Write a JavaScript program that will accept two dates and calculate the number of days between them.
Problem 7
Write a JavaScript function to accept a value for x from the user and compute the value of :

sin( x 2 ) + cos(1 / x 2 )

Ranjan Parekh
School of Education Technology, Jadavpur University, Calcutta, India
www.geocities.com/rparekhju/

15

Das könnte Ihnen auch gefallen