Previous Page TOC Next Page See Page



- 4 -
General Objects and Functions


The separation of language capabilities into those provided by Server JavaScript and those provided by Client JavaScript through the use of Objects means that the size of each runtime system can be kept down to a minimum. Only those objects and methods that are actually supported by either version need to be included.

There are, however, some objects and stand-alone functions that need to be made available in both Server and Client JavaScript. In this chapter each of these objects and the properties and methods they contain are examined in detail. The topics to be discussed include the following:


The String Object


It's easy to consider variables that contains strings as just that, variables. In actual fact, all strings are stored internally in a String object.



Note:

Brendan Eich—the Netscape developer largely responsibly for the development of JavaScript—describes objects like the String object as First Class objects.


The String object is basically the same as all of the objects you have encountered previously—it contains properties and methods. But unlike objects you create yourself, which require a call to the new operator to instantiate them, new String objects are created automatically by JavaScript whenever they are needed. Take the following as an example:

var aString = "This is a string" ;

This statement actually creates a new variable called aString and assigns a String object to it that contains the value "This is a string." (It should also be noted that the string literal "This is a string" is treated internally by JavaScript as a String object.)

In addition, by taking advantage of the new operator, a string also can be defined using the statement

var aString = new String("This is a string");

Properties


The String object makes only one of its properties publicly accessible. This is the .length property.

string.length

The length property reflects the number of characters, or the length, of a string object. In addition, it is a read-only property. This means that the value of the property cannot be manually altered by the programmer.

To use the length property in a program, simply append .length to any string variable:

var aString = "This is a string" ;
document.write( aString.length );

This example causes the number "16" to be displayed on the web page.

String Literals as Objects

Because JavaScript treats string literals as true String objects, you can actually use a string literal wherever you would normally use a string variable. For example, the following code

var aString = "This is a string" ;
var aStringLength = aString.length ;

can be written as

var aStringLength = "This is a string".length ;

The same is true for all of the methods listed in the following sections, although exactly why you would want to use this feature is best left up to the imagination.

Methods


The methods supported by the String object fall into one of two categories:


String Contents Methods

The first set of methods supported by the String object all perform functions related to the contents of the string. By using these methods you can locate specific characters in a string, obtain a subsection of the string, or alter its case.

string.charAt()

The charAt() method returns the value of a character located at a specific position in a String object. The syntax for the charAt() method is as follows:

stringname.charAt( index )

Index is an integer literal or a variable between 0 and string.length-1. All strings in JavaScript are indexed from left to right, with the first character in the string located in index position 0, the second in index position 1, the third in index position 2, and so on. As a result, the index position of the last character in the string is located in index position string.length minus one and not string.length.

To print out the third character in a string you would write something like the following:

var aString = "This is a string" ;
var character = aString.charAt( 2 ) ; 
document.write( character );


Note:

If you set an index value that is larger than the length of the string, JavaScript returns an empty string.



string.indexOf()

The indexOf() method returns the position of a specific character within a string. The syntax for the indexOf() method is

stringname.indexOf( character, [starting_index])

Character can be either a string literal or a string variable that represents the character you want to search for. Take the following as an example:

var aString = "This is a string" ;
var number = aString.indexOf( 'a' );
document.write( number );

The statement aString.indexOf( 'a' ) is used to search the content of aString for the first occurrence of the letter 'a.' The index value returned to number, 8 in this example—remembering that the index position of the first character is 0.



Note:

If indexOf() cannot find the character in the string, a value of -1 is returned.


The indexOf() method also supports a second format which makes use of the optional starting_index parameter. By default, indexOf() starts searching at the first character in the string. However, if you include a starting_index value, the search commences at the character in the position indicated by starting_index:

var aString = "This is a string" ;
var number = aString.indexOf( 's' , 8 );
document.write( number );

The value assigned to number is 10 because that is the index position of the first 's' located after the character in index position 8, which you already know is an 'a'.

string.lastIndexOf()

The lastIndexOf() method returns the position of a specific character within a string, but instead of searching the string from left to right, as was the case for indexOf(), lastIndexOf() searches the string from right to left. The syntax for the lastIndexOf() method is

stringname.lastIndexOf( character, [starting_index])

Character can be either a string literal or a string variable that represents the character you want to search for. Take the following as an example:

var aString = "This is a string" ;
var number = aString.lastIndexOf( 's' );
document.write( number );

This time, the statement aString.lastIndexOf( 's' ) is used to search the content of aString for the last occurrence of the letter 's', by searching the string from right to left. The index value returned to number in this example is 10.



Note:

Like indexOf(), if lastIndexOf() cannot find the character in the string, a value of -1 is returned.


By using the optional starting_index parameter of the lastIndexOf() method, you can search the string from a specific staring point. By default, lastIndexOf() starts searching at the index location represented by string.length-1. However, if you include a starting_index value, the search commences at the character in the position indicated by starting_index and continues searching to the right of this character until it reaches the beginning of the string:

var aString = "This is a string" ;
var number = aString.indexOf( 's' , 8 );
document.write( number );

The value assigned to number is 6 because that is the index position of the first 's' located to the right of index position 8.

string.substring()

The substring() method is used to return a subsection of a string. The syntax for substring() follows:

stringname.substring( indexA, indexB )

IndexA and indexB represent index positions within the string. JavaScript uses these two values to determine which part of the string you want returned.

If the value of indexA is less than indexB, then a string starting with the character at position indexA and ending with the character prior to position indexB is returned. On the other hand, if indexA is greater than indexB, then the a string starting with the character at position indexB and ending with the character prior to position indexA is returned. Finally, if indexA and indexB are equal, an empty string is returned.

As a result, to select just the word "string" from the string aString, you could write either of the following:

var newString = aString.substring( 10 , 16 ) ;
var newString = aString.substring( 16 , 10 ) ;

There is also a special version of the substring() method which takes only one parameter. In this case, the section of the string starting at the index position indicated by the parameter and finishing at the end of the string is returned.

For this reason, because the word "string" in aString is at the very end of the string, you also could use the following format:

var newString = aString.substring( 10 ) ;

string.toLowerCase()

The toLowerCase() method is used to return a new string with all the letters in the existing string converted to lower case. The syntax for the toLowerCase() method is

stringname.toLowerCase()

Take for example

var sometext = "THIS IS SOME TEXT";
document.write(sometext.toLowerCase() )

This prints out "this is some text" on the Web page.

string.toUpperCase()

The toUpperCase() method is used to return a new string with all the letters in the existing string converted to upper case. The syntax for the toUpperCase() method is:

stringname.toUpperCase()

The toUpperCase() method basically performs the reverse operation to that of the toLowerCase() method:

var sometext = "this is some text";
document.write(sometext.toUpperCase() )

This prints out "THIS IS SOME TEXT" on the Web page.

HTML Text Formatting Methods

One of the most common uses of JavaScript is for dynamic HTML creation, or in other words, building Web pages on the fly. To assist with this task, the String object includes a collection of methods which build the HTML code for many of the standard HTML tags.

string.anchor()

The anchor() method returns the HTML code needed to insert an anchor into a Web page. The syntax for anchor()follows:

stringname.anchor( anchorname )

Anchorname is the text associated with the NAME property in the <A> tag. To understand what is going on here, look at the following example:

var someText = "The top of a page";
var anAnchor = someText.anchor( "Heading" );
document.write( anAnchor );

The second line of code in this example creates a new string called anAnchor containing the following text:

<A NAME="Heading">The top of a page</A>

This text represents the code needed to define an anchor using HTML. Once created, to include this anchor code into your Web page all you need to do is write it out using the document.write() or document.writeln() methods in Client JavaScript, or the write() function in Server JavaScript.



Note:

Refer to Appendix B, "HTML Guide" for more information about the meaning of the HTML tags themselves.



string.fontcolor()

The fontcolor() method returns the HTML code needed to change the color of a block of text on a Web page. The syntax for fontcolor() is as follows:

stringname.fontcolor( fontcolor )

The contents of variable stringname represents the text you want displayed and fontcolor represent the new color as either a hexadecimal RGB triplet or a color string literal. (Appendix E, "Colors by Name and Hex Value" contains a list of valid color string literals and their corresponding RGB hexadecimal triplet values.)

The HTML code returned by the fontcolor() method looks like

<FONT COLOR=fontcolor>contents of stringname</FONT>

string.fontsize()

The fontsize() method returns the HTML code needed to change the size of a block of text on a Web page. The syntax for fontsize() is as follows:

stringname.fontsize( fontsize )

The contents of variable stringname represents the text to be displayed, and fontsize is the size of the text. There are currently seven font sizes recognized by JavaScript—1 being the smallest and 7 the largest. In addition, relative font sizes are also supported by using positive or negative numbers such as -2 or +1.

The HTML code returned by the fontsize() method takes the form:

<FONT SIZE=fontsize>contents of stringname</FONT>

string.link()

The link() method returns the HTML code needed to include a hyperlink on a Web page. The syntax for link()follows:

stringname.link( href )

The contents of stringname are used as the link text and the contents of href as the destination for the hyperlink.

The HTML code returned by the link() method takes the form:

<A HREF=href>contents of stringname</A>

Character Formatting

The remaining HTML text formatting methods all create HTML tag code that falls into the category of character formatting. Table 4.1 lists each of these methods and describes the nature of the HTML code created by them.

Table 4.1 Character formatting methods for the String object.



String Method HTML Code created
stringname.big() <BIG>contents of stringname </BIG>
stringname.blink() <BLINK>contents of stringname </BLINK>
stringname.bold() <B>contents of stringname </B>
stringname.fixed() <FIXED>contents of stringname </FIXED>
stringname.italics() <I>contents of stringname </I>
stringname.small() <SMALL>contents of stringname </SMALL>
stringname.strike() <STRIKE>contents of stringname </STRIKE>

The Math Object


The Math object provides a set of constant mathematical values and a collection of methods that perform most of the common mathematical operations found in programming language today.

To use any of the properties or methods of the Math object in your JavaScript code, simply treat the object as you would any other:

var number = 9;
var newnumber = Math.sqrt( number );

This code creates a variable called number and assigns a value of 9 to it. On the second line, another variable called newnumber is created. newnumber is assigned the value returned by calling the square root method of the Math object with number as an argument.

Properties


Table 4.2 list all of the public properties that can be accessed using the Math object. Note that all of these properties are read-only because they fall into the category of constants.

Table 4.2 Properties of the Math object

Math Property Approximate Value Description
Math.E 2.718 Euler's constant E—the base for natural logarithms.
Math.LN2 0.693 The natural logarithm of two.
Math.LN10 2.302 The natural logarithm of ten.
Math.LOG2E 1.442 The base 2 logarithm of E.
Math.LOG10E 0.434 The base 10 logarithm of E.
Math.PI 3.14159 The ratio of the circumference of a circle to its diameter.
Math.SQRT1_2 0.707 The square root of 0.5.
Math.SQRT2 1.414 The square root of 2.


Note:

Because of the problems associated with floating point numbers, you should always use the constants provided by the Math object wherever it is appropriate to do so.



Methods


Table 4.3 lists all of the methods currently supported by the Math object. For each method, the table lists the syntax and a short description of its use.

Table 4.3 Methods provided by the Math object

Math Method Description
Math.abs( num ) Returns the absolute value of num.
Math.acos( num ) Returns the arc cosine of num in radians.
Math.asin( num ) Returns the arc sine of num in radians.
Math.atan( num ) Returns the arc tangent of num in radians.
Math.atan2( x,y ) Returns the angle of the polar coordinate corresponding to the cartesian coordinate x,y.
Math.ceil( num ) Returns the lowest integer that is greater than or equal to num.
Math.cos( num ) Returns the cosine of num in radians.
Math.exp( num ) Returns E—Euler's constant—raised to the power of num.
Math.floor( num ) Returns the largest integer which is less than or equal to num.
Math.log( num ) Returns the natural logarithm—base E—of num.
Math.max( num1, num2 ) Returns the larger of the two numbers.
Math.min( num1, num2 ) Returns the smallest of the two numbers.
Math.pow(base, exponent) Returns base raised to the exponent power.
Math.random() Returns a random number. (This function is not currently supported on all platforms.)
Math.round( num ) Return num rounded to the nearest integer.
Math.sin( num ) Returns the sine of num in radians.
Math.sqrt( num ) Returns the square root of num.
Math.tan( num ) Returns the tangent of num.

The Date Object


Unlike most other languages that include a built-in date data type, in JavaScript there is no explicit date data type. JavaScript does provide a Date object that not only removes the need for a date data type but also introduces a valuable collection of methods enabling you to manipulate the contents of Date objects.

To use the Date object in JavaScript, you first need to create a new Date object using the new statement and the special built-in Date() constructor function. The Date() constructor takes one of the following forms:

dateObjectName = new Date();
dateObjectName = new Date("month day, year hours:minutes:seconds")
dateObjectName = new Date(year, month, day);
dateObjectName = new Date(year, month, day, hours, minutes, sec );

If you use the first form new Date(), a new Date object containing the current time and date is created. The second form takes a string or string literal like "January 1, 1996 08:30:00". The third form takes three integers or integer literals and only sets the date components of the Date object. And finally, the forth form also uses integers, but sets both the time and date components.

In the third and fourth form, the value of year integer is calculated by subtracting 1900 from the year, so that for 1996 you need to set year to 96 and the month value is an integer between 0 and 11. January = 0, February = 1, March = 2, and so on. For example,

aDate = new Date(96,9,22);

Would create an instance of the Date object called aDate set to October 22, 1996.



Note:

Internally, JavaScript stores all dates as an integer number representing the number of milliseconds since January 1, 1970 00:00:00. This basically means that you cannot use the Date object to hold any date earlier that January 1 1970.



Methods


There are no public properties associated with a Date object. Instead, to access or alter the contents of a Date object, you need to use one of the many built-in date methods. For example, to create a Date object that holds a date exactly one year from the present time you could write the following:

var currentdate = new date();
var currentyear = currentdate.getYear();
var nextyear = currentyear + 1;
currentdate.setYear( nextyear );

After creating a new Date object and setting it to the current date, the getYear() function is called to obtain an integer representation of the year. One is added to this currentyear integer and then the resulting value nextyear is used to set the year component of currentdate to the following year.

Set and Get Methods

The Date object contains methods to set and get the values assigned to each different component of a date. Table 4.4 list all of the set and get methods, including their syntax and a brief description of each ones' use.

Table 4.4. Set and get methods provided by the Date object

Date Method Description
datename.getDate() Returns the day of the month from object datename as an integer, where 1 is the first day of the month.
datename.getDay() Returns the day of the week from object datename as an integer, where 0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday and 6 = Saturday.
datename.getHours() Returns the hour of the day from object datename as an integer between 0 and 23.
datename.getMinutes() Returns the minute value from object datename as an integer between 0 and 59.
datename.getMonth() Returns the month value from object datename as an integer between 0 and 11. January = 0, February = 1, March = 2 and so on.
datename.getSeconds() Returns the seconds value from object datename as an integer between 0 and 59.
datename.getTime() Returns a numeric value corresponding to the time represented by object datename. The number returned equals the number of milliseconds since January 1970 00:00:00.
datename.getTimeZoneoffset() Returns the difference between local time and GMT in minutes.
datename.getYear() Returns the year value from object datename as an integer. The value is calculated by subtracting 1900 from the year, so that 1996 returns a value of 96.
datename.setDate( dayvalue ) Sets the day of the month value for object datename as an integer, where dayvalue is a number between 1 and 31.
datename.setHours( hour ) Sets the hour of the day for object datename. Hour is an integer between 0 and 23.
datename.setMinutes( min ) Sets the minutes value of object datename. Min is an integer between 0 and 59.
datename.setMonth( month ) Sets the month value of object datename. Month is an integer between 0 and 11.
datename.setSeconds( secs ) Sets the seconds value of object datename. Secs is an integer between 0 and 59.
datename.setTime( date ) Sets the value of object datename. Date is a date expressed as the number of milliseconds since January 1970 00:00:00.
datename.setYear( year ) Sets the year value of object datename as an integer. The value of year is calculated by subtracting 1900 from the actual year.

String Values

There are currently three methods in the Date object that can be used to convert the contents of a Date object to a string. Table 4.5 outlines the use of these three methods.

Table 4.5. Methods used to convert a Date object to a string.

Date Method Description
datename.toGMTString() Returns the date represented by object datename as a string. The value of the string is formatted based on GMT. Because my location is 10 hours ahead of GMT, a string like "Sun, 31 Dec 1995 22:30:00 GMT" is returned.
datename.toLocaleString() Returns the date represented by object datename as a string. The value of the string is formatted based on local time. The format of this string is controlled by your computer platform and its date preferences. On my system, a string like "01/01/96 08:30:00" is returned.
datename.toString() Returns a string value in a form similar to "Mon Jan 01 08:30:00 EAS 1996". Again this format may vary somewhat from computer system to computer system.


Note:

As a rule you shouldn't use the toString() method in your own code, because it is technically an internal method automatically called by JavaScript when needed. For example, the use of


document.write( datename );

is preferable to

document.write( datename.toString() );

which actually gives the same result.


Date to Integer Conversion

There are two special methods which have not yet been discussed. These methods are used to convert a date represented either as a string or a set of integers into a single integer value representing the number of milliseconds since January 1970 00:00:00.



Note: The parse() and UTC() methods outlined in this section are both called static methods. Basically this means that you call them using the base object Date instead of an individual Date object. For example, to call parse() you need to use

Date.parse()

and not

dateobjectname.parse().


Date.parse()

The parse() method takes a string date and returns an integer representing the number of milliseconds since January 1970 00:00:00. The syntax of the parse() method is

Date.parse( datestring )

Datestring is a string of the form "Mon, 1 Jan 1996 08:80:00". The parse() method can also recognize a variety of other date formats including the following:

var number = Date.parse( "1 Jan 1996 08:80:00" );
var number = Date.parse( "1 Jan 1996" );
var number = Date.parse( "Jan 1, 1996" );
var number = Date.parse( "01/01/1996" );
var number = Date.parse( "01/01/96" );

In all of the preceding examples, JavaScript assumes you are referring to local time. The parse() method can also be used to calculate dates and times based on Universal Coordinated Time or GMT. The following examples demonstrate some of the formats recognized when using UTC coding:

var number = Date.parse( "Sun, 31 Dec 1995 22:30:00 GMT" );
var number = Date.parse( "31 Dec 1995 22:30:00 GMT" );
var number = Date.parse( "12/31/1995 22:30:00 GMT" );
var number = Date.parse( "31 Dec 1995 22:30:00 GMT +1000" );
var number = Date.parse( "12/31/1995 22:30:00 GMT +1000" );

Date.UTC()

The UTC() method returns the number of milliseconds in a date since January 1, 197000:00:00 GMT as opposed to local time. The syntax of the UTC() method is as follows:

Date.UTC( year, month, day, [hrs], [min], [sec])

Year, month, day, hrs, min, and u are all integers that abide by the following rules:

The main reason for the existence of the UTC() method is so the value of new Date objects can be defined using GMT time instead of local time. The following example demonstrates how this is done:

gmtDate = new Date( Date.UTC(95, 12, 31, 23, 30, 0) );

Pre-defined Functions


Apart from built-in objects and methods, JavaScript also includes a small set of redefined functions which are not directly associated with any specific objects. These functions are:



Note:

Netscape refers to these functions as Top Level functions.



The eval() Function


The eval() takes a string and processes it as though it was an expression or a block of JavaScript commands. Its syntax is as follows:

returnvalue = eval( evalstring );

If the contents of evalstring evaluate to an expression, then the result of the expression is stored in returnvalue. Alternatively, if the string contains JavaScript commands they are executed as though they were a part of the JavaScript program.

The following example demonstrates how eval() can be used:

var somestring = "1 + 1";
display.write( somestring );
display.write( " = " );

display.write( eval( somestring ) );

If this code was run on a Web page, the result would be a line of text that said:

1 + 1 = 2

The eval( somestring ) statement in the last line of code used to evaluate the contents of somestring, which in this case contains an expression. Once evaluated, the result of this expression, '2', is returned to the document.write() statement so that it can be displayed on the Web page.

The parseFloat() Function


The parseFloat() function examines the contents of a string. If it encounters a valid number, it is converted into a floating point value. This value is returned as the function result. The syntax of parseFloat() is as follows:

returnfloat = parseFloat( stringfloat );

Stringfloat is a string containing a number stored in string format that adheres to the following rules.

"NaN" on any other platform, indicating that the value is not a number. (See the inNaN() function later for more information.)


The parseInt() Function


The parseInt() function examines the contents of a string. If it encounters a valid number, the number is converted into an integer value. This value is then returned as the function result. The syntax of parseInt()follows:

returnint = parseInt( stringint, [ radix ] );

Stringint is a string containing a number stored in string format and radix is an optional parameter that indicates the base of the number stored in the string. A radix of 10 indicates that the number is a decimal, a radix of 8 indicates that the number is a Octal, and a radix of 16 indicates that the number is Hexadecimal

Only strings that comply with the following rules are converted to an integer value:

"NaN" on any other platform, indicating that the value is not a number. (See the inNaN() function later for more information.)

The following example outlines some of the possible valid string formats for the parseInt() function.

var somenumber = parseInt("1010", 2) ;
var somenumber = parseInt("217", 8) ;
var somenumber = parseInt("15", 10) ;
var somenumber = parseInt("FA00", 16) ;
var somestring = "1234" ;

var somenumber = parseInt( somestring ) ;

The isNaN() Function


When JavaScript encounters a string that cannot be converted to a number using either parseInt() or parseFloat(), it returns one of two possible values depending on the computer platform.

If you are on a Windows based system a zero value is returned, but on all other systems a special result called a NaN (Not a Number) is returned.

On UNIX systems you can test whether the result was a NaN using the isNaN() function. The format of the isNaN() function follows:

var boolvalue = isNaN( somenumber );

Somenumber is the result returned from either a parseInt() or parseFloat() function. If the content of somenumber is a NaN then the value true is assigned to boolvalue otherwise it is assigned a value of false.

Summary


To incorporate basic string formatting, date management, and mathematical functions into JavaScript, a group of special stand-alone objects and method have been created. These objects exist in both Client and Server JavaScript.

In addition, JavaScript also includes a small number of Top Level functions as a part of the basic language. These functions let you evaluate and parse strings containing expressions, JavaScript commands, and integer or floating point values.

Previous Page Page Top TOC Next Page See Page