Professional Documents
Culture Documents
Internet programming
Fourth Grade
( Lecture 8 )
It makes sense to call the list above global functions rather than global
methods because the functions are called globally and not any objects.
Anyway, you can also call these functions methods, since they are methods of
the global object where they run. In a web browser, the global object is the
browser window. Then isNaN() is actually a window method: window.isNaN().
2
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
decodeURI(string)
Syntax
decodeURI(encodedString)
Description
Returns the unencoded value of an encoded Uniform Resource Identifier (URI)
string.
Example
< script >
var myString="£ €& ?@ And this is some test text";
document.write(encodeURI(myString) + "< br> ");
//%C2%A3%E2%82%AC &?@%20And%20this%20is%20some%20test%20text
document.write(decodeURI(encodeURI(myString)));
// £ €& ?@ And this is some test text
< /script >
decodeURIComponent(string)
Syntax
decodeURIComponent(encodedString)
Description
Returns the unencoded value of an encoded component of a Uniform Resource
Identifier (URI) string.
Example
< script >
var myString="£ €& ?@ And this is some test text";
document.write(encodeURIComponent(myString) + "< br>");
// %C2%A3%E2%82%AC%26%3F%40%20And%20this%20is%20some%20test%20text
document.write(decodeURIComponent(encodeURIComponent(myString)));
// £ €& ?@ And this is some test text
< /script >
encodeURI(string)
Syntax
encodeURI(mystring)
3
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
Description
The encodeURI() function is used to encode a URI.
This function encodes special characters, except: , / ? : @ & = + $ #
(Use encodeURIComponent() to encode these characters).
Example
< script >
var myString="£ €& ?@ And this is some test text";
document.write(encodeURI(myString) + "< br>");
// %C2%A3%E2%82%AC & ?@%20And%20this%20is%20some%20test%20text
document.write(decodeURI(encodeURI(myString)));
// £ €& ?@ And this is some test text
< /script >
encodeURIComponent(string)
Syntax
encodeURIComponent(string)
Description
Encodes a text string to a valid component of a Uniform Resource Identifier
(URI) by encoding reserved characters.
This function encodes special characters. In addition, it encodes the following
characters: , / ? : @ & = + $ #
Example
< script >
var myString="£ €& ?@ And this is some test text";
document.write(encodeURIComponent(myString) + "< br>");
// %C2%A3%E2%82%AC%26%3F%40%20And%20this%20is%20some%20test%20text
document.write(decodeURIComponent(encodeURIComponent(myString)));
// £ €& ?@ And this is some test text
< /script >
escape(string)
Syntax
escape(String)
4
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
Description
Encodes a string by replacing all special or reserved characters with their
encoded equivalents.
Example
< script >
var myString=" £ €& ?@ And this is some test text";
document.write(escape(myString) + "< br> ");
// %A3%u20AC%26%3F@%20And%20this%20is%20some%20test%20text
document.write(unescape(escape(myString)));
// £ €& ?@ And this is some test text
< /script >
eval(string)
Syntax
eval(string)
Description
Evaluates JavaScript source code and then executes it.
Example
< script >
var mySimpleExpression = "document.write(‘This is a test’); ";
eval(mySimpleExpression); // This is a test
var myExpression = new String("10*10");
eval(myExpression.toString());
< /script >
isFinite(numval)
Syntax
isFinite(Num)
Description
Returns a Boolean value indicating whether the supplied number is finite.
Example
< script >
var myNum = 10;
if (isFinite(myNum)) {
// this will execute
5
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
isNaN(numval)
Syntax
isNaN(numval)
Description
Determines whether the passed value will be treated as a number or not, by
returning boolean value.
Example
< script >
document.write(isNaN(10) + "< br >"); // false
document.write(isNaN("10") + "< br >"); // false
document.write(isNaN("ABCD") + "< br >"); // true
document.write(isNaN("25CC") + " < br > "); // true
< /script >
parseFloat(string)
Syntax
parseFloat(numstring)
Description
Returns a floating point number from a string representing a number.
Example
< script >
document.write(parseFloat("3.99") + "< br >"); // 3.99
document.write(parseFloat("399e-2") + "< br >"); // 3.99
document.write(parseFloat("0.0399E+2") + "< br>"); // 3.99
var x = "3.99";
document.write(parseFloat(x) + "< br > "); // 3.99
6
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
OBJECTS
JavaScript is an Object Oriented Programming (OOP) language. A
programming language can be called object-oriented if it provides four
basic capabilities to developers:
Encapsulation: the capability to store related information, whether
data or methods, together in an object.
Aggregation: the capability to store one object inside another object.
Inheritance: the capability of a class to rely upon another class (or
number of classes) for some of its properties and methods.
Polymorphism: the capability to write one function or method that works
in a variety of different ways.
7
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
8
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
9
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
10
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
Example:
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
function addPrice(amount){
with(this){
price = amount;
}
}
function book(title, author){
this.title = title;
11
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
this.author = author;
this.price = 0;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("C++ how to program", "Paul");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
The output
Book title is : C++ how to program
Book author is : Paul
Book price is : 100
Math Object
The Math object’s methods enable you to conveniently perform many common
mathematical calculations. As shown previously, an object’s methods are called
by writing the name of the object followed by a dot (.) and the name of the
method. In parentheses following the method name are arguments to the
method. For example, to calculate the square root of 900 you might write
var result = Math.sqrt(900 );
which first calls method Math.sqrt to calculate the square root of the number
contained in the parentheses (900), then assigns the result to a variable. The
number 900 is the argument of the Math.sqrt method. The above statement
would return30.Some Math-object methods are summarized in the following
table:
Method Description
abs(x) Returns the absolute value of a number (x).
acos(x) Returns the arccosine (in radians) of a number.
asin(x) Returns the arcsine (in radians) of a number.
atan(x) Returns the arctangent (in radians) of a number.
12
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
Example:
<html>
<head>
<title>JavaScript Math abs() Method</title>
</head>
<body>
<script type="text/javascript">
var value = Math.abs(-1);
document.write("First Test Value : " + value );
var value = Math.abs(null);
document.write("<br>Second Test Value : " + value );
var value = Math.abs(20);
document.write("<br>Third Test Value : " + value );
var value = Math.abs("string");
document.write("<br>Fourth Test Value : " + value );
</script>
</body>
13
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
</html>
Output
First Test Value : 1
Second Test Value : 0
Third Test Value : 20
Fourth Test Value : NaN
Example 2:
<html>
<head>
<title>Some JavaScript Math Method</title>
</head>
<body>
<script type="text/javascript">
var value = Math.ceil(45.20);
document.write("ceil method Value : " + value );
var value = Math.floor(45.20);
document.write("<br>floor method Value : " + value );
var value = Math.round( 45.20 );
document.write("<br>round method Value : " + value );
</script>
</body>
</html>
14
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
Math properties
The Math object defines several properties that represent commonly used
mathematical constants. These are summarized in the following table. [Note:
By convention, the names of constants are written in all uppercase letters so that
they stand out in a program.]
15
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
Property Description
Euler's constant and the base of natural logarithms,
E
approximately 2.718.
LN2 Natural logarithm of 2, approximately 0.693.
LN10 Natural logarithm of 10, approximately 2.302.
LOG2E Base 2 logarithm of E, approximately 1.442.
LOG10E Base 10 logarithm of E, approximately 0.434.
Ratio of the circumference of a circle to its diameter,
PI
approximately 3.14159.
Square root of 1/2; equivalently, 1 over the square root of
SQRT1_2
2, approximately 0.707.
SQRT2 Square root of 2, approximately 1.414.
Example:
<html>
<head>
<title>JavaScript Math Properties</title>
</head>
<body>
<script type="text/javascript">
var property_value = Math.E
document.write("Property E Value is :" + property_value+"<br>");
property_value = Math.LN2
document.write("Property LN2 Value is : " + property_value+"<br>");
property_value = Math.LN10
document.write("Property LN10 Value is : " + property_value+"<br>");
property_value = Math.LOG2E
document.write("Property LOG2E Value is : " + property_value+"<br>");
property_value = Math.PI
document.write("Property PI Value is : " + property_value+"<br>");
</script>
</body>
</html>
16
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
String Object
Fundamentals of Characters and Strings
Characters are the building blocks of JavaScript programs. Every program is
composed of a sequence of characters grouped together meaningfully that’s
interpreted by the computer as a series of instructions used to accomplish a task.
A string is a series of characters treated asa single unit. A string may include
letters, digits and various special characters, such as +, -, *, /, and $. A string is
an object of type String. String Literals or string constants are written as a
sequence of characters in double or single quotation marks, as follows:
"John Q. Doe" (a name)
'9999 Main Street' (a street address)
"Waltham, Massachusetts" (a city and state)
'(201) 555-1212' (a telephone number)
A string may be assigned to a variable in a declaration. The declaration:
var color ="blue";
Initializes variable color with the String object containing the string "blue".
Strings can be compared via the relational (<, <=, >and>=) and equality
operators (==, ===, !=and !==). The comparisons are based on the Unicode
values of the corresponding characters. For example, the expression
"h" < "H" evaluates to false because lowercase letters have higher Unicode
values.
17
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
Method Description
charAt(index) Returns the character at the specified index.
Returns a number indicating the Unicode value of
charCodeAt(index)
the character at the given index.
Concatenates its argument to the end of the string
on which the method is invoked. The original
string is not modified; instead a New String is
concat(string)
returned. This method is the same as adding two
strings with the string-concatenation operator +
(e.g.,s1.concat(s2)is the same as s1 + s2).
Searches for the first occurrence of substring
starting from position index in the string that
indexOf(substring, invokes the method.The method returns the starting
index of sub string in the source string or –1 if
index)
Substring is not found. If the index argument is not
provided, the method begins searching from index
0 in the source string.
Returns the index within the calling String object
lastIndexOf(substring,
of the last occurrence of the specified value, or -1
index)
if not found.
match() Used to match a regular expression against a string.
Used to find a match between a regular expression
replace(searchString,
and a string, and to replace the matched substring
replaceString)
with a new substring.
Executes the search for a match between a regular
search()
expression and a specified string.
Extracts a section of a string and returns a new
slice(start, end)
string.
Splits the source string into an array of strings
(tokens), where its String argument specifies the
split(string)
delimiter (i.e., the characters that indicate the end
of each token in the source string)
18
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
Example:
<html>
<head>
<title>JavaScript string Properties</title>
</head>
<body>
<script type="text/javascript">
var s1 ="this is text";
var s2="THIS IS TEXT";
document.write("Property charAt : " + s1. charAt(0) +"<br>");
document.write("Property charAt : " + s1. charAt(5) +"<br>");
document.write("Property index of : " + s1. indexOf ("x")+"<br>");
document.write("Property last index of : " + s1. lastIndexOf ("t")+"<br>");
document.write("Property to upper case : " + s1. toUpperCase()+"<br>");
var ss=s1. concat(" here");
document.write("Property concat : " + ss+"<br>" );
document.write("Property replace : " + s2. replace("TEXT", "STRING")
+"<br>");
document.write("Property to lower case : " + s2. toLowerCase()+"<br>");
</script>
</body>
</html>
19
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
Date Object
The Date object is a datatype built into the JavaScript language. Date
objects are created with the new Date() as shown below.
Once a Date object is created, a number of methods allow you to operate on it.
Most methods simply allow you to get and set the year, month, day,
hour, minute, second, and millisecond fields of the object, using either
local time zone or based on World Time Standard’s Coordinated Universal
Time (abbreviated UTC).
The ECMAScript standard requires the Date object to be able to represent
any date and time, to millisecond precision, within 100 million days before
or after 1/1/1970. This is a range of plus or minus 273,785 years, so
JavaScript can represent date and time till the year 275755.
Syntax
You can use any of the following syntaxes to create a Date object using Date()
constructor.
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ] )
Note: Parameters in the brackets are always optional.
Most methods of the Date object have a local time zone and a UTC version.
Date-object methods are summarized in the following table:
20
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
Method Description
Date() Returns today's date and time
getDate() Returns a number from 1 to 31 representing the
getUTCDate() day of the month in local time or UTC.
Returns a number from 0 (Sunday) to
getDay()
6(Saturday) representing the day of the week in
getUTCDay()
local time or UTC.
getFullYear() Returns the year as a four-digit number in local
getUTCFullYear() time or UTC.
getHours() Returns a number from 0 to 23 representing
getUTCHours() hours since midnight in local time or UTC.
Returns a number from 0 to 999 representing
getMilliseconds() the number of milliseconds in local time or
getUTCMilliseconds() UTC, respectively. The time is stored in hours,
minutes, seconds and milliseconds.
getMinutes() Returns a number from 0 to 59 representing the
getUTCMinutes() minutes for the time in local time or UTC.
Returns a number from 0 (January) to 11
getMonth()
(December) representing the month in local
getUTCMonth()
time or UTC.
getSeconds() Returns a number from 0 to 59 representing the
getUTCSeconds() seconds for the time in local time or UTC.
Returns the numeric value of the specified date
getTime() as the number of milliseconds since January 1,
1970, 00:00:00 UTC.
Returns the time-zone offset in minutes for the
getTimezoneOffset()
current locale.
setDate(val) Sets the day of the month (1 to 31) in local time
setUTCDate(val) or UTC.
Sets the year in local time or UTC. The second
setFullYear(y, m, d) and third arguments representing the month and
the date are optional. If an optional argument is
setUTCFullYear(y, m, d)
not specified, the current value in the Date
object is used.
Sets the hour in local time or UTC. The second,
setHours(h, m, s, ms) third and fourth arguments, representing the
minutes, seconds and milliseconds, are optional.
setUTCHours(h, m, s, ms)
If an optional argument is not specified, the
current value in the Date object is used.
21
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
Example:
<html>
<head>
<title>JavaScript Date Methods</title>
</head>
<body>
<script type="text/javascript">
var dt = Date();
document.write("Date and Time : " + dt +"<br>");
var dt1 = new Date("December 25, 2020 23:15:00");
22
Internet Programming LEC. 8 Asst. Lec.: Sura Nasser
23