home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Dynamic HTML: The Definitive Reference, 2rd Ed.Dynamic HTML: The Definitive ReferenceSearch this book

12.5. Core Objects

argumentsNN 3 IE 4 ECMA 1

Every function—while it is executing—has an arguments object, which is accessible as a property of the function. The object is created automatically, and cannot be created outside of the function context that owns it. For example, consider a typical function definition:

function myFunc( ) {
     // function statements
}

A statement inside the function can access the arguments object by the following reference:

arguments

This object always contains the callee property, which is a reference to the very same function (explained in the callee property discussion). But you can also use the arguments object to access each parameter variable value through array notation. In the above example, a statement inside the myFunc( ) function can access the passed parameter value with the following reference:

arguments[0]

See the arguments property discussion of the Function object later in this chapter for practical applications.

Properties

callee

length

Methods

None.

calleeNN 6 IE 5(Mac)/5.5(Win) ECMA 1

Read-only
Provides a reference to the function that created the arguments object. This property provides the essential reference to the current function, which an anonymous function would require for it to be called in a recursive construction.

Example

myObj.doThis = function(input) {
      // function statements that act on parameter value
      if (!someCondition) {
           arguments.callee(input);
      }
}

Value

Function object reference.

lengthNN 3 IE 4 ECMA 1

Read-only
Returns the number of arguments passed to the function in its current invocation. The number is not influenced by the number of parameter variables defined for the function.

Example

function myFunc( )
    for (var i = 0; i < arguments.length; i++) {
        ...
    }
}

Value

Integer.

ArrayNN 3 IE 4 ECMA 1

An array is an ordered collection of one or more pieces of data. JavaScript array entries may be of any data type, and you can mix different data types in the same array. Each entry in an array has an index assigned to it. The default behavior is for the index to be a zero-based integer (the first entry has an index of zero). An index value may also be a string, but the string index acts like a property name of an array object, and does not influence the numeric indices (which is why string-indexed entries cannot be iterated via the array's length property, but can be iterated via a for-in loop). Separate sets of integer- and string-indexed items can coexist within the same array object.

Accessing an entry in an array requires the name of the array and the index in square brackets:

cars[0]
cars["Ford"]

You may also create an array of arrays to simulate multidimensional arrays. A reference to an item in a two-dimensional array uses syntax as follows:

myArray[x][y]

The number of entries in a JavaScript array (its length) can vary over time. Therefore, you do not have to initialize an empty array to a specific size (nor is there any particular advantage to doing so). To add a new entry to an array of indeterminant length, assign the value to the next higher array index value:

cars[cars.length] = "Bentley";

A shortcut array creation technique is available starting in IE 4 and Navigator 4, using square brackets to contain values in literal notation.

Creating an Array

var myArray = new Array( );
var myArray = new Array(sizeInteger);
var myArray = new Array(element0, element1, ..., elementN);
var myArray = [element0, element1, ..., elementN];

Properties

constructor

length

prototype

Methods

concat( )

join( )

pop( )

push( )

reverse( )

shift( )

slice( )

sort( )

splice( )

toLocaleString( )

toString( )

unshift( )

constructorNN 4 IE 4 ECMA 1

Read/Write
This is a reference to the function that created the instance of an Array object—the native Array( ) constructor function in browsers.

Example

if (myVar.constructor == Array) {
    // process native string
}

Value

Function object reference.

lengthNN 3 IE 4 ECMA 1

Read/Write
Provides a count of the number of numerically-indexed entries stored in the array. If the constructor function used to create the array specified a preliminary length, the length property reflects that amount, even if data does not occupy every slot.

Example

for (var i = 0; i < myArray.length; i++) {
    ...
}

Value

Integer.

prototypeNN 3 IE 4 ECMA 1

Read/Write
This is a property of the static Array object. Use the prototype property to assign new properties and methods to future instances of arrays created in the current document. For example, the following function creates a return-delimited list of elements in an array in reverse order:

function formatAsList( ) {
    var output = "";
    for (var i = this.length - 1; i >= 0; i--) {
        output += this[i] + "\n";
    }
    alert(output);
}

To give an array that power, assign this function reference to a prototype property whose name you want to use as the method to invoke this function:

Array.prototype.showReverseList = formatAsList;

If a script creates an array at this point:

var stooges = new Array("Moe", "Larry", "Curly", "Shemp");

the new array has the showReverseList( ) method available to it. To invoke the method, the call is:

stooges.showReverseList( );

You can add properties the same way. These allow you to attach information about the array (its creation time, for example) without disturbing the ordered sequence of array data. When a new document loads into the window or frame, the static Array object starts fresh again.

Example

Array.prototype.created = "";

Value

Any data, including function references.

concat( )NN 4 IE 4 ECMA 3

concat(item1[, item2[, ...itemN]])

Returns an array that combines the current array object with one or more array objects (or other values) specified as the method parameter(s):

var combinedArray = myArray1.concat(myArray2, someValue);

Neither of the original arrays is altered in the process.

Returned Value

An Array object.

Parameters

item1...itemN
Any JavaScript value, including another array.

join( )NN 3 IE 4 ECMA 1

join(["delimiterString"])

Returns a string consisting of a list of items (as strings) contained by an array. The delimiter character(s) between items is set by the parameter to the method. Note that an array's items are only those items that are accessible via an integer index. Items referenced via string index values are treated as properties of the array object, and are thus independent of integer indexed values (the two sets can coexist in a single array without conflict). The join( ) method works only with the integer-indexed items.

Returned Value

String.

Parameters

delimiterString
Any string of characters. Nonalphanumeric characters must use URL-encoded equivalents (%0D for carriage return). The default delimiter string is a comma character.

pop( )NN 4 IE 5.5(Win) ECMA 2

Returns the value of the last item in an array and removes it from the array. The length of the array decreases by one.

Returned Value

Any JavaScript value.

Parameters

None.

push( )NN 4 IE 5.5(Win) ECMA 2

push(item1[, item2[, ...itemN]])

Appends one or more items to the end of an array. The length of the array increases by one.

Returned Value

The value pushed into the array.

Parameters

item1...itemN
Comma-delimited list of one or more JavaScript values, including object references.

reverse( )NN 3 IE 4 ECMA 1

Reverses the order of items in the array and returns a copy of the array in the new order. Not only does the reverse( ) method rearrange the values in the array, but it also returns a copy of the reversed array.

Returned Value

An Array object.

Parameters

None.

shift( )NN 4 IE 5.5(Win) ECMA 2

Returns the value of the first item in an array and removes it from the array. The length of the array decreases by one.

Returned Value

Any JavaScript value.

Parameters

None.

slice( )NN 4 IE 4 ECMA 2

slice(startIndex[, endIndex]) 

Returns an array that is a subset of contiguous items from the main array. Parameters determine where the selection begins and ends.

Returned Value

An Array object.

Parameters

startIndex
A zero-based integer of the first item of the subset from the current array.

endIndex
An optional zero-based integer of the last item of the subset from the current array. If omitted, the selection is made from the startIndex position to the end of the array.

splice( )NN 4 IE 5.5(Win) ECMA 2

splice(startIndex, deleteCount[, item1[, item2[, ...itemN]]]) 

Removes one or more contiguous items from within an array and, optionally, inserts new items in their places. The length of the array adjusts itself accordingly.

Returned Value

An Array object containing removed items.

Parameters

startIndex
A zero-based integer of the first item of the subset from the current array.

deleteCount
An integer denoting how many items from the startIndex position are to be removed from the array.

item1...itemN
Comma-delimited list of JavaScript values to be inserted into the array in place of removed items. The number of items does not have to equal deleteCount.

toLocaleString( )NN 6 IE 5.5(Win) ECMA 2

Returns a comma-delimited string of values, theoretically in a format tailored to the language and customs of the browser's default language. Implementation details vary with browser and data type. IE 5.5 and later converts numbers of all kinds to strings with two digits to the right of the decimal, but triggers an error for object references. Netscape 6 leaves integers in their original format and displays object references as [object objectType]. The ECMA standard leaves such interpretations up to the browser maker.

Returned Value

Comma-delimited string.

Parameters

None.

toString( ) NN 3 IE 4 ECMA 1

Returns a comma-delimited string of values, identical to using the Array.join( ) method with a comma parameter. All values are converted to some string equivalent, including objects ([object] in IE/Windows; [object objectType] in IE 5/Macintosh and Netscape 6).

Returned Value

Comma-delimited string.

Parameters

None.

unshift( )NN 4 IE 5.5(Win) ECMA 2

unshift(item1[, item2[, ...itemN]])

Inserts one or more items at the beginning of an array. The length of the array increases by the number of items added, and the method returns the new length of the array.

Returned Value

Integer.

Parameters

item1...itemN
Comma-delimited list of one or more JavaScript values.

BooleanNN 3 IE 4 ECMA 1

A Boolean object represents any value that evaluates to true or false. By and large, you don't have to worry about the Boolean object because the browsers automatically create such objects for you when you assign a true or false value to a variable. Quoted versions of these values are treated only as string.

Creating a Boolean Object

var myValue = new Boolean( );
var myValue = new Boolean(BooleanValue);
var myValue = BooleanValue;

Properties

constructor

prototype

Methods

toString( )

valueOf( )

constructorNN 4 IE 4 ECMA 1

Read/Write
This is a reference to the function that created the instance of a Boolean object—the native Boolean( ) constructor function in browsers.

Example

if (myVar.constructor == Boolean) {
    // process native string
}

Value

Function object reference.

prototypeNN 3 IE 4 ECMA 1

Read/Write
This is a property of the static Boolean object. Use the prototype property to assign new properties and methods to future instances of a Boolean value created in the current document. See the Array.prototype property description for examples. There is little need to create new prototype properties or methods for the Boolean object.

Example

Boolean.prototype.author = "DG";

Value

Any data, including function references.

toString( )NN 4 IE 4 ECMA 1

Returns the object's value as a string data type. You don't need this method in practice, because the browsers automatically convert Boolean values to strings when they are needed for display in alert dialogs or in-document rendering.

Returned Value

"true" | "false"

Parameters

None.

valueOf( )NN 4 IE 4 ECMA 1

Returns the object's value as a Boolean data type. You don't need this method when you create Boolean objects by simple value assignment.

Returned Value

Boolean value: true | false.

Parameters

None.

DateNN 2 IE 3 ECMA 1

The Date object is a static object that generates instances by way of several constructor functions. Each instance of a Date object is a snapshot of the date and time, measured in milliseconds relative to zero hours on January 1, 1970. Negative millisecond values represent time before that date; positive values represent time since that date.

The typical way to work with dates is to generate a new instance of the Date object, either for now or for a specific date and time (past or future, using the client local time). Then use the myriad of available date methods to get or set components of that time (e.g., minutes, hours, date, month). Browsers internally store a date as the millisecond value at Coordinated Universal Time (UTC, which is essentially the same as Greenwich Mean Time, or GMT). When you ask a browser for a component of that time, it automatically converts the value to the local time zone of the browser based on the client computer's control panel setting for the clock and time zone. If the control panel is set incorrectly, time and date calculations may go awry.

Early versions of scriptable browsers had numerous bugs when working with the Date object. One resource that explains the fundamental operations within the Date object (and bugs) can be found at http://developer.netscape.com/viewsource/goodman_dateobject.html.

Creating a Date Object

var now = new Date( );
var myDate = new Date("month dd, yyyy hh:mm:ss");
var myDate = new Date("month dd, yyyy");
var myDate = new Date(yy, mm, dd, hh, mm, ss);
var myDate = new Date(yy, mm, dd);
var myDate = new Date(milliseconds);

Properties

constructor

prototype

Methods

 

getDate( )

getDay( )

getFullYear( )

getHours( )

getMilliseconds( )

getMinutes( )

getMonth( )

getSeconds( )

getTime( )

getTimezoneOffset( )

getUTCDate( )

getUTCDay( )

getUTCFullYear( )

getUTCHours( )

getUTCMilliseconds( )

getUTCMinutes( )

getUTCMonth( )

getUTCSeconds( )

getVarDate( )

getYear( )

parse( )

setDate( )

setFullYear( )

setHours( )

setMilliseconds( )

setMinutes( )

setMonth( )

setSeconds( )

setTime( )

setUTCDate( )

setUTCFullYear( )

setUTCHours( )

setUTCMilliseconds( )

setUTCMinutes( )

setUTCMonth( )

setUTCSeconds( )

setYear( )

toDateString( )

toGMTString( )

toLocaleDateString( )

toLocaleString( )

toLocaleTimeString( )

toString( )

toTimeString( )

toUTCString( )

UTC( )

valueOf( )

 
 
constructorNN 4 IE 4 ECMA 1

Read/Write
This is a reference to the function that created the instance of a Date object—the native Date( ) constructor function in browsers.

Example

if (myVar.constructor == Date) {
    // process native string
}

Value

Function object reference.

prototypeNN 3 IE 4 ECMA 1

Read/Write
This is a property of the static Date object. Use the prototype property to assign new properties and methods to future instances of a Date value created in the current document. See the Array.prototype property description for examples.

Example

Date.prototype.author = "DG";

Value

Any data, including function references.

getDate( )NN 2 IE 3 ECMA 1

Returns the calendar date within the month specified by an instance of the Date object.

Returned Value

Integer between 1 and 31.

Parameters

None.

getDay( )NN 2 IE 3 ECMA 1

Returns an integer corresponding to a day of the week for the date specified by an instance of the Date object.

Returned Value

Integer between 0 and 6. Sunday is 0, Monday is 1, and Saturday is 6.

Parameters

None.

getFullYear( )NN 4 IE 4 ECMA 1

Returns all digits of the year for the date specified by an instance of the Date object.

Returned Value

Integer. Navigator 4 goes no lower than zero. Internet Explorer and Netscape 6 return negative year values.

Parameters

None.

getHours( )NN 2 IE 3 ECMA 1

Returns a zero-based integer corresponding to the hours of the day for the date specified by an instance of the Date object. The 24-hour time system is used.

Returned Value

Integer between 0 and 23.

Parameters

None.

getMilliseconds( )NN 4 IE 4 ECMA 1

Returns a zero-based integer corresponding to the number of milliseconds past the seconds value of the date specified by an instance of the Date object.

Returned Value

Integer between 0 and 999.

Parameters

None.

getMinutes( )NN 2 IE 3 ECMA 1

Returns a zero-based integer corresponding to the minute value for the hour and date specified by an instance of the Date object.

Returned Value

Integer between 0 and 59.

Parameters

None.

getMonth( )NN 2 IE 3 ECMA 1

Returns a zero-based integer corresponding to the month value for the date specified by an instance of the Date object. That this method's values are zero-based frequently confuses scripters at first.

Returned Value

Integer between 0 and 11. January is 0, February is 1, and December is 11.

Parameters

None.

getSeconds( )NN 2 IE 3 ECMA 1

Returns a zero-based integer corresponding to the seconds past the nearest full minute for the date specified by an instance of the Date object.

Returned Value

Integer between 0 and 59.

Parameters

None.

getTime( )NN 2 IE 3 ECMA 1

Returns a zero-based integer corresponding to the number of milliseconds since January 1, 1970, to the date specified by an instance of the Date object.

Returned Value

Integer.

Parameters

None.

getTimezoneOffset( )NN 2 IE 3 ECMA 1

Returns a zero-based integer corresponding to the number of minutes difference between GMT and the client computer's clock for an instance of the Date object. Time zones to the west of GMT are positive values; time zones to the east are negative values. Numerous bugs plagued this method in early browsers, especially Macintosh versions.

Returned Value

Integer between -720 and 720.

Parameters

None.

getUTCDate( )NN 4 IE 4 ECMA 1

Returns the calendar date within the month specified by an instance of the Date object but in the UTC time stored internally by the browser.

Returned Value

Integer between 1 and 31.

Parameters

None.

getUTCDay( )NN 4 IE 4 ECMA 1

Returns an integer corresponding to a day of the week for the date specified by an instance of the Date object but in the UTC time stored internally by the browser.

Returned Value

Integer between 0 and 6. Sunday is 0, Monday is 1, and Saturday is 6.

Parameters

None.

getUTCFullYear( )NN 4 IE 4 ECMA 1

Returns all digits of the year for the date specified by an instance of the Date object but in the UTC time stored internally by the browser.

Returned Value

Integer. Navigator 4 goes no lower than zero. Internet Explorer and Netscape 6 return negative year values.

Parameters

None.

getUTCHours( )NN 4 IE 4 ECMA 1

Returns a zero-based integer corresponding to the hours of the day for the date specified by an instance of the Date object but in the UTC time stored internally by the browser. The 24-hour time system is used.

Returned Value

Integer between 0 and 23.

Parameters

None.

getUTCMilliseconds( )NN 4 IE 4 ECMA 1

Returns a zero-based integer corresponding to the number of milliseconds past the seconds value of the date specified by an instance of the Date object but in the UTC time stored internally by the browser.

Returned Value

Integer between 0 and 999.

Parameters

None.

getUTCMinutes( )NN 4 IE 4 ECMA 1

Returns a zero-based integer corresponding to the minute value for the hour and date specified by an instance of the Date object but in the UTC time stored internally by the browser.

Returned Value

Integer between 0 and 59.

Parameters

None.

getUTCMonth( )NN 4 IE 4 ECMA 1

Returns a zero-based integer corresponding to the month value for the date specified by an instance of the Date object but in the UTC time stored internally by the browser. That this method's values are zero-based frequently confuses scripters at first.

Returned Value

Integer between 0 and 11. January is 0, February is 1, and December is 11.

Parameters

None.

getUTCSeconds( )NN 4 IE 4 ECMA 1

Returns a zero-based integer corresponding to the seconds value past the nearest full minute of the date specified by an instance of the Date object but in the UTC time stored internally by the browser.

Returned Value

Integer between 0 and 59.

Parameters

None.

getVarDate( )NN n/a IE 4 ECMA n/a

Returns a date value in a format (called VT_DATE) suitable for a variety of Windows-oriented applications, such as ActiveX controls and VBScript. Not for use with JavaScript date calculations.

Returned Value

VT_DATE format value (not for JavaScript use).

Parameters

None.

getYear( )NN 2 IE 3 ECMA n/a

Returns a number corresponding to the year of an instance of the Date object, but exhibits irregular behavior. In theory, the method should return the number of years the date object represents since 1900. This would produce a one- or two-digit value for all years between 1900 and 1999. However, when you reach 2000, the pattern fails. Instead of producing values starting with 100, the getYear( ) method, some browsers return the same four-digit value as getFullYear( ). For this reason, it is best to use getFullYear( ) whenever possible (but observe the browser compatibility for that method). Note that this method is not an ECMA-supported method, whereas getFullYear( ) is.

Returned Value

Integer between 0 and 99 for the years 1900 to 1999; four-digit integer starting with 2000 for some browsers, or a continuation (100+) for others.

Parameters

None.

parse( )NN 2 IE 3 ECMA 1

parse("dateString")

Static Date object method that returns the millisecond equivalent of the date specified as a string in the parameter.

Returned Value

Date in milliseconds.

Parameters

dateString
Any valid string format equivalent to that derived from a Date object. See toString( ), toGMTString( ), and toLocaleString( ) methods for sample formats.

setDate( )NN 2 IE 3 ECMA 1

setDate(dateInt)

Sets the date within the month for an instance of the Date object. If you specify a date beyond the end of the object's current month, the object recalculates the date in the succeeding month. For example, if a Date object is set to December 25, 2002, you can find out the calendar date ten days later with the following construction:

myDate.setDate(myDate.getDate( ) + 10);

After this calculation, the value of myDate is the equivalent of January 4, 2003.

Returned Value

New date in milliseconds.

Parameters

dateInt
Date integer.

setFullYear( )NN 4 IE 4 ECMA 1

setFullYear(yearInt)

Assigns the year for an instance of the Date object.

Returned Value

New date in milliseconds.

Parameters

yearInt
Integer. Navigator 4 allows digits no lower than zero. Internet Explorer and NN 6 allow negative year values.

setHours( )NN 2 IE 3 ECMA 1

setHours(hourInt)

Sets the hours of the day for an instance of the Date object. The 24-hour time system is used. If you specify an hour beyond the end of the object's current day, the object recalculates the time in the succeeding day(s).

Returned Value

New date in milliseconds.

Parameters

hourInt
Zero-based integer.

setMilliseconds( )NN 4 IE 4 ECMA 1

setMilliseconds(msInt)

Sets the number of milliseconds past the seconds value for an instance of the Date object.

Returned Value

New date in milliseconds.

Parameters

msInt
Zero-based integer of milliseconds.

setMinutes( )NN 2 IE 3 ECMA 1

setMinutes(minuteInt)

Sets the minute value for the hour and date of an instance of the Date object.

Returned Value

New date in milliseconds.

Parameters

minuteInt
Zero-based integer.

setMonth( )NN 2 IE 3 ECMA 1

setMonth(monthInt)

Sets the month value for the date of an instance of the Date object. That this method's values are zero-based frequently confuses scripters at first.

Returned Value

New date in milliseconds.

Parameters

monthInt
Zero-based integer. January is 0, February is 1, and December is 11. Assigning higher values increases the object to the succeeding year.

setSeconds( )NN 2 IE 3 ECMA 1

setSeconds(secInt)

Sets the seconds value past the nearest full minute for an instance of the Date object.

Returned Value

New date in milliseconds.

Parameters

secInt
Zero-based integer.

setTime( )NN 2 IE 3 ECMA 1

setTime(msInt)

Sets an instance of the Date object to the number of milliseconds since January 1, 1970.

Returned Value

New date in milliseconds.

Parameters

msInt
Integer of milliseconds.

setUTCDate( )NN 4 IE 4 ECMA 1

setUTCDate(dateInt)

Sets the date within the month of an instance of the Date object but in the UTC time stored internally by the browser. If you specify a date beyond the end of the object's current month, the object recalculates the date in the succeeding month.

Returned Value

New UTC date in milliseconds.

Parameters

dateInt
Integer.

setUTCFullYear( )NN 4 IE 4 ECMA 1

setUTCFullYear(yearInt)

Sets all digits of the year for an instance of the Date object but in the UTC time stored internally by the browser.

Returned Value

New UTC date in milliseconds.

Parameters

yearInt
Integer. Navigator 4 allows values no lower than zero. Internet Explorer and NN 6 allow negative year values.

setUTCHours( )NN 4 IE 4 ECMA 1

setUTCHours(hourInt)

Sets the hours of the day for an instance of the Date object but in the UTC time stored internally by the browser. The 24-hour time system is used.

Returned Value

New UTC date in milliseconds.

Parameters

hourInt
Zero-based integer.

setUTCMilliseconds( )NN 4 IE 4 ECMA 1

setUTCMilliseconds(msInt)

Sets the number of milliseconds past the seconds value of an instance of the Date object but in the UTC time stored internally by the browser.

Returned Value

New UTC date in milliseconds.

Parameters

msInt
Zero-based integer.

setUTCMinutes( )NN 4 IE 4 ECMA 1

setUTCMinutes(minuteInt)

Sets the minute value for the hour and date of an instance of the Date object but in the UTC time stored internally by the browser.

Returned Value

New UTC date in milliseconds.

Parameters

minuteInt
Zero-based integer.

setUTCMonth( )NN 4 IE 4 ECMA 1

setUTCMonth(monthInt)

Sets the month value for an instance of the Date object but in the UTC time stored internally by the browser. That this method's values are zero-based frequently confuses scripters at first.

Returned Value

New UTC date in milliseconds.

Parameters

monthInt
Zero-based integer. January is 0, February is 1, and December is 11. Assigning higher values increases the object to the succeeding year.

setUTCSeconds( )NN 4 IE 4 ECMA 1

setUTCSeconds(secInt)

Sets the seconds value past the nearest full for an instance of the Date object but in the UTC time stored internally by the browser.

Returned Value

New UTC date in milliseconds.

Parameters

secInt
Zero-based integer.

setYear( )NN 2 IE 3 ECMA n/a

setYear(yearInt)

Sets the year of an instance of a Date object. Use setFullYear( ) if the browser versions you support allow it. Note that this method is not an ECMA-supported method, whereas setFullYear( ) is.

Returned Value

New date in milliseconds.

Parameters

yearInt
Four-digit (and sometimes two-digit) integers representing a year.

toDateString( )NN 6 IE 5.5(Win) ECMA 3

Returns a string consisting only of the date portion of an instance of a Date object. The precise format is under the control of the browser and language, but U.S. English versions of both IE 6 for Windows and Netscape 6 return values in the format Ddd Mmm dd yyyy.

Returned Value

String.

Parameters

None.

toGMTString( )NN 2 IE 3 ECMA 1

Returns a string version of the GMT value of a Date object instance in a standardized format. This method does not alter the original Date object. For use in newer browsers, the toUTCString( ) method is recommended in favor of toGMTString( ).

Returned Value

String in the following format: dayAbbrev, dd mmm yyyy hh:mm:ss GMT. For example:

Mon 05 Aug 2002 02:33:22 GMT

Parameters

None.

toLocaleDateString( )NN 6 IE 5.5(Win) ECMA 3

Returns a string consisting only of the date portion of an instance of a Date object. The precise format is under the control of the browser and language. IE 6 for Windows returns a value in the format fullDay, fullMonth dd, yyyy; Netscape 6 returns fullDay fullMonth dd yyyy.

Returned Value

String.

Parameters

None.

toLocaleTimeString( )NN 6 IE 5.5(Win) ECMA 3

Returns a string consisting only of the time portion of an instance of a Date object. The precise format is under the control of the browser and language. IE 6 for Windows returns a value in the format [h]h:mm:ss xM; Netscape 6 returns hh:mm:ss.

Returned Value

String.

Parameters

None.

toTimeString( )NN 6 IE 5.5(Win) ECMA 3

Returns a string consisting only of the time portion of an instance of a Date object. The precise format is under the control of the browser and language.

Returned Value

String.

Parameters

None.

toUTCString( )NN 4 IE 4 ECMA 1

Returns a string version of the UTC value of a Date object instance in a standardized format. This method does not alter the original Date object. For use in newer browsers, the toUTCString( ) method is recommended in favor of toGMTString( ).

Returned Value

String in the following format: dayAbbrev dd mmm yyyy hh:mm:ss GMT. For example:

Mon 05 Aug 2002 02:33:22 GMT

Parameters

None.

UTC( )NN 2 IE 3 ECMA 1

UTC(yyyy, mm, dd[, hh[, mm[, ss[, msecs]]]]) 

This is a static method of the Date object that returns a numeric version of the date as stored internally by the browser for a Date object. Unlike parameters to the Date object constructor, the parameter values for the UTC( ) method must be in UTC time for the returned value to be accurate. This method does not generate a date object, as the Date object constructor does.

Returned Value

Integer of the UTC millisecond value of the date specified as parameters.

Parameters

yyyy
Four-digit year value.

mm
Two-digit month number (0-11).

dd
Two-digit date number (1-31).

hh
Optional two-digit hour number in 24-hour time (0-23).

mm
Optional two-digit minute number (0-59).

ss
Optional two-digit second number (0-59).

msec
Optional milliseconds past the last whole second (0-999).

valueOf( )NN 4 IE 4 ECMA 1

Returns the object's value.

Returned Value

Integer millisecond count.

Parameters

None.

ErrorNN 6 IE 5(Win) ECMA 3

Browsers that implement try/catch exception handling automatically create an instance of the Error object whenever an error occurs during script processing. You can also create an Error object instance that you explicitly throw. The catch portion of the try/catch construction receives the Error object instance as a parameter, which scripts can examine to learn the details of the error, as exposed by the object's properties.

Creating an Error Object

var myError = new Error("errorMessage");

Properties

constructor

description

fileName

lineNumber

message

name

number

prototype

Methods

toString( )

constructorNN 6 IE 5(Win) ECMA 3

Read/Write
Provides a reference to the function that created the instance of an Error object—the native Error( ) constructor function in browsers.

Example

if (myVar.constructor == Error) {
    // process native string
}

Value

Function object reference.

descriptionNN n/a IE 5(Win) ECMA n/a

Read/Write
Provides a plain-language description of the error, frequently the same as appears in the IE script error dialog. Use the newer message property if possible.

Example

if (myError.description.indexOf("Object expected") != -1) {
    // handle "object expected" error
}

Value

String.

fileNameNN 6 IE n/a ECMA n/a

Read/Write
Specifies the URL of the page in which the script error occurred. This information appears in the JavaScript Console window for each reported error.

Example

var sourceFile = myError.fileName;

Value

URL string.

lineNumberNN 6 IE n/a ECMA n/a

Read/Write
Specifies the number of the line in the source code where the current script error occurred. This information appears in the JavaScript Console window for each reported error.

Example

var errorLine = myError.lineNumber;

Value

Number in string format.

messageNN 6 IE 5.5(Win) ECMA 3

Read/Write
Provides a plain-language description of the error. There is no standard for the format or content of such messages.

Example

if (myError.description.indexOf("defined") != -1) {
    // handle error for something being undefined
}

Value

String.

nameNN 6 IE 5.5(Win) ECMA 3

Read/Write
This is a string that sometimes indicates the type of the current error. The default value of this property is Error. But the browser may also report types EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError, and, if supported by the browser, a specific W3C DOM error type.

Example

if (myError.name == "SyntaxError") {
    // handle syntax error
}

Value

String.

prototypeNN 6 IE 5(Win) ECMA 3

Read/Write
This is a property of the static Error object. Use the prototype property to assign new properties and methods to future instances of a Error object created in the current document. See the Array.prototype property description for examples.

Example

Error.prototype.custom = true;

Value

Any data, including function references.

toString( )NN 6 IE 5(Win) ECMA 3

Returns a string representation of the object, but the values differ between browser families. IE returns [object Error], while Netscape 6 returns a concatenation of the name and message properties.

Returned Value

String.

Parameters

None.

FunctionNN 2 IE 3 ECMA 1

A function is a group of one or more script statements that can be invoked at any time during or after the loading of a page. Invoking a function requires nothing more than including the function name with a trailing set of parentheses inside another script statement or as a value assigned to an event handler attribute in an HTML tag.

Since the first scriptable browsers, a function is created by the act of defining it inside a script element:

function funcName( ) {...}

More recent browsers also allow the use of a constructor function, but this syntax is usually more complex than defining a function.

Functions may be built to receive zero or more parameters. Parameters are assigned to comma-delimited parameter variables defined in the parentheses pair following the function name:

function doSomething(param1, param2, ... paramN) {...}

A parameter value may be any JavaScript data type, including object references and arrays. There is no penalty for not supplying the same number of parameters to the function as are defined for the function. The function object receives all parameters into an array (called arguments), which script statements inside the function may examine to extract parameter data.

A function returns execution to the calling statement when the function's last statement has executed. A value may be returned to the calling statement via the return statement. Also, a return statement anywhere else in the function's statements aborts function statement execution at that point and returns control to the calling statement (optionally with a returned value). If one branch of a conditional construction in a function returns a value, each branch, including the main branch, must also return a value, even if that value is null (IE tends to be more forgiving if you don't balance return statements, but it's good programming practice just the same).

Functions have ready access to all global variables that are defined outside of functions anywhere in the document. But variables defined inside a function (the var keyword is required) are accessible only to statements inside the function.

To reference a function object that is defined elsewhere in the document, use the function name without its parentheses. For example, to assign a function to an event handler property, the syntax is:

objReference.eventHandlerProperty = functionName;

Starting with Version 4 browsers, you may nest functions inside one another:

function myFuncA( ) {
    statements
    function myFuncB( ) {
        statements
    }
}

Nested functions (such as myFuncB) can be invoked only by statements in its next outermost function.

All functions belong to the window in which the function is defined. Therefore, if a script must access a function located in a sibling frame, the reference must include the frame and the function name:

parent.otherFrame.someFunction( )

Creating a Function

function myFunction([param1[, param2[,...paramN]]]) {
    statement(s)
}
var myFunction = new Function([param1[,...paramN], "statement1[; ...statementN;"])
objectRef.methodName = function([param1[, param2[,...paramN]]]) {
    statement(s)
}

Properties

arguments

arity

caller

constructor

length

prototype

Methods

apply( ) toString( ) call( ) valueOf( )
argumentsNN 3 IE 4 ECMA 1

Read-only
Returns an arguments object that contains values passed as arguments to the function. Script statements inside the function can access the values through array syntax, which has numeric index values that correspond to incoming parameter values in the order in which they were passed. The content of the arguments array is independent of the parameter variables defined for the function. Therefore, if the function defines two parameter variables but the calling statement passes 10 parameters, the arguments array captures all 10 values in the order in which they were passed. Statements inside the function may then examine the length of the arguments array and extract values as needed. This allows one function to handle an indeterminate number of parameters if the need arises.

For most browsers, you can simply begin the reference to the object with the name of the property (e.g., arguments[2]). But some older browsers require the name of the enclosing function object, as well. All browsers recognize the longer version.

Example

function myFunc( )
    for (var i = 0; i < myFunc.arguments.length; i++) {
        ...
    }
}

Value

An arguments object.

arityNN 4 IE n/a ECMA n/a

Read-only
Returns an integer representing the number of parameters that are defined for the function. This property may be examined in a statement outside of the function, perhaps in preparation of parameters to be passed to the function. Returns the same value as the length property.

Example

var paramCount = myFunction.arity;

Value

Integer.

callerNN 3 IE 4 ECMA n/a

Read-only
Returns a reference to a function object that contained the statement invoking the current function. This property is readable only by script statements running in function whose caller you wish to reference. Omitted in Netscape 6.0, but back in subsequent versions.

Example

function myFunc( )
    if (myFunc.caller == someFuncZ) {
        // process when this function is called by someFuncZ
    }
}

Value

Function object.

constructorNN 4 IE 4 ECMA 1

Read/Write
This is a reference to the function that created the instance of a Function object—the native Function( ) constructor function in browsers.

Example

if (myVar.constructor == Function) {
    // process native function
}

Value

Function object reference.

lengthNN 4 IE 4 ECMA 1

Read-only
Returns an integer representing the number of parameters that are defined for the function. This property may be examined in a statement outside of the function, perhaps in preparation of parameters to be passed to the function.

Example

var paramCount = myFunction.length;

Value

Integer.

prototypeNN 3 IE 4 ECMA 1

Read/Write
This is a property of the static Function object. Use the prototype property to assign new properties and methods to future instances of functions created in the current document. See the Array.prototype property description for examples.

Example

Function.prototype.author = "DG";

Value

Any data, including function references.

apply( )NN 6 IE 5.5(Win) ECMA 3

apply([thisObjectRef[, argumentsArray]])

Invokes the current function, optionally specifying an object to be used as the context for which any this references in the function applies. Parameters to the function (if any) are contained in array that is passed as the second parameter of the apply( ) method. The method can be used with anonymous or named functions. Usage of this method is rare, but provides flexibility that is helpful if your script should encounter a reference to a function and needs to invoke that function, particularly within an object's context.

Consider a script function that is assigned as a method of a custom object:

// function definition
function myFunc(parm1, parm2, parm3) {
    // statements
}
// custom object constructor
function customObj(arg1, arg2) {
    this.property1 = arg1;
    this.property2 = arg2;
    this.method1 = myFunc;
}
var myObjA = new CustomObj(val1, val2);
var myObjB = new CustomObj(val3, val4);

The most common way to execute the myFunc( ) function is as a method of one of the objects:

myObjA.method1(parmValue);

But you can invoke the function from a reference to the function, and make the function believe it is being invoked through one of the objects:

myFunc.apply(myObjB, [parmVal1, parmVal2, parmVal3]);

If the function (myFunc in this example) has a statement with the this keyword in it, that term becomes a reference to the object context passed as the first parameter to the apply( ) method (myObjB in this example).

Returned Value

None.

Parameters

thisObjectRef
Reference to an object that is to act as the context for the function.

argumentsArray
An array with items that are values to be passed to the function. Array entries are passed to the function in the same order as they are organized in the array.

call( )NN 6 IE 5.5(Win) ECMA 3

call([thisObjectRef[, arg1[, arg2,[...argN]]]])

Invokes the current function, optionally specifying an object to be used as the context for which any this references in the function applies. Parameters to the function (if any) are contained in a comma-delimited list passed as additional parameters to the call( ) method. Other than the way parameters to the function are assembled, the call( ) and apply( ) methods perform the same tasks. See the apply( ) method for more details.

Returned Value

None.

Parameters

thisObjectRef
Reference to an object that is to act as the context for the function.

arg1,...argN
A comma-delimited list of parameters values to be passed to the function.

toString( )NN 4 IE 4 ECMA 1

Returns the object's value (script statement listing and function wrapper) as a string data type. You don't need this method in practice because the browsers automatically convert values to strings when they are needed for display in alert dialogs or in-document rendering.

Returned Value

String.

Parameters

None.

valueOf( )NN 4 IE 4 ECMA 1

Returns the object's value. When displaying the value, such as in an alert dialog box, the browser converts the value to a string, but the true value is an instance of the Function object.

Returned Value

A function object reference.

Parameters

None.

GlobalNN 2 IE 3 ECMA 1

The Global object lives in every window or frame of a JavaScript-enabled browser (it is created for you automatically). You don't ever reference the object explicitly, but you do reference its properties and methods to accomplish tasks such as converting strings to numbers (via the parseInt( ) or parseFloat( ) methods). Properties act as constants, and thus evaluate to themselves. As an object with global scope, it exposes its members to script statements throughout the page.

Properties

Infinity

NaN

undefined

Methods

 

atob( )

btoa( )

decodeURI( )

decodeURIComponent( )

encodeURI( )

encodeURIComponent( )

escape( )

eval( )

GetObject( )

isFinite( )

isNaN( )

parseInt( )

parseFloat( )

ScriptEngine( )

ScriptEngineBuildVersion( )

ScriptEngineMajorVersion( )

ScriptEngineMinorVersion( )

unescape( )

unwatch( )

watch( )

 
 
InfinityNN 4 IE 4 ECMA 1

Read-only
Provides a numerical positive infinity (or negated with the - operator). We're talking a practical, as opposed to a theoretical, infinity here. Any number smaller than Number.MIN_VALUE or larger than Number.MAX_VALUE is an infinite value in the JavaScript world. How mundane!

Example

var authorEgo = Infinity;

Value

Infinity

NaNNN 3 IE 4 ECMA 1

Read-only
This is a value that is not-a-number. JavaScript returns this value when a numerical operation yields a non-numerical result because of a flaw in one of the operands. If you want to test whether a value is not a number, use the isNaN( ) global function rather than comparing to this property value. This global property is the value that Number.NaN evaluates to.

Value

NaN

undefinedNN 6 IE 5.5(Win) ECMA 2

Read-only
While the undefined data type has been in ECMAScript and browsers since very early times, only recently was it also elevated to a formal property of the Global object. Despite the recent compatibility ratings, you can use its data type (accessed in string form via the typeof operator) comfortably in older browsers.

Value

undefined

decodeURI( )NN 6 IE 5.5(Win) ECMA 3

decodeURI("encodedURI")

Returns a string with most URI-encoded values in the parameter restored to their original symbols. Operates only on escaped (encoded) characters that are encodable via the encodeURI( ) method.

Returned Value

A string.

Parameters

encodedURI
A string containing a relative or complete encoded URI.

atob( ), btoa( )NN 4 IE n/a ECMA n/a

atob("base64EncodedData")
btoa("stringToBeEncoded")

These methods let you convert arbitrary strings (including strings conveying characters representing binary data and Unicode values) to a 65-character subset of the U.S.-ASCII character set. Encoding in this so-called base64 scheme allows any data to be conveyed along even the most rudimentary transport mechanism. You can read about the rationale and internal mechanisms of the encoding/decoding conversions in RFC 1521 of the Internet Engineering Task Force (http://www.ietf.org/rfc/rfc2045.txt).

Use the btoa( ) method to encode string data into the base64 scheme. The resulting encoded data will consist of ASCII characters a-z, A-Z, 0-9, and three symbols (/, +, =). Use the atob( ) method to decode base64 encoded data back to its original version.

Returned Value

A string.

Parameters

base64EncodedData
A string containing base64 data either encoded on the client or received as part of a document from a server that performs its own encoding.

stringToBeEncoded
A string characters to be encoded to base64 for internal or external use. For example, an encoded value could be assigned to the value property of an input element for submission to a server process designed to receive base64 data.

decodeURIComponent( )NN 6 IE 5.5(Win) ECMA 3

decodeURIComponent("encodedURIComponent")

Returns a string with all URI-encoded values in the parameter restored to their original symbols. Intended for use on data portions of a URI excluding the protocol.

Returned Value

A string.

Parameters

encodedURIComponent
A string containing a relative or complete encoded URI, or portions thereof.

encodeURI( )NN 6 IE 5.5(Win) ECMA 3

encodeURI("URIString")

Returns a string with most URI-encodable values in the parameter converted to their escaped versions (e.g., a space character is converted to %20). This method excludes the following characters from conversion:

;  /  ?  :  @  &  =  +  $  ,  #

These characters are valid symbols in URI strings as-is, and should not be converted, and the conversion might invalidate the URI.

Returned Value

A string.

Parameters

URIString
A string containing a relative or complete plain-text URI.

encodeURIComponent( )NN 6 IE 5.5(Win) ECMA 3

encodeURIComponent("URIComponentString")

Returns a string with all characters except Latin character set letters A through Z (upper and lower cases), digits 0 through 9, and a set of URI-friendly symbols (- _ . ! ~ * ( ) ' space) converted to their escaped versions (% symbol followed by the hexadecimal version of their Unicode value). Intended for use on data portions of a URI excluding the protocol.

Returned Value

A string.

Parameters

URIComponentString
A string containing a relative or complete plain-text URI, or portions thereof.

escape( )NN 2 IE 3 ECMA |1|

escape("string"[, 1])

Returns a URL-encoded version of the string passed as a parameter to the function. URL encoding converts most nonalphanumeric characters (except * _ + - . / and, in IE, @) to hexadecimal values (such as %20 for the space character). URL-encoded strings do not normally encode the plus symbol because those symbols are used to separate components of search strings. If you must have the plus symbol encoded as well, Navigator 4 (only) offers a second parameter (a numeral 1) to turn on that switch for the method. Note that in IE 5.5 for Windows and Netscape 6, this method has been deprecated in favor of the encodeURI( ) and encodeURIComponent( ) methods. This method has been removed from the ECMA 3 specification.

Returned Value

A string.

Parameters

string
Any string value.

eval( )NN 2 IE 3 ECMA 1

eval("string")

Returns an object reference of the object described as a string in the parameter of the function. For example, if a form has a sequence of text fields named entry1, entry2, entry3, and so on, you can still use a for loop to cycle through all items by name if you let the eval( ) function convert the string representation of the names to object references:

for (var i = 1; i <=5; i++) {
    oneField = eval("document.forms[0].entry" + i);
    oneValue = oneField.value;
    ...
}

Be aware, however, that the eval( ) method is perhaps the most inefficient and performance-draining method of the entire JavaScript language. There are many other, far more efficient, ways to reference a document tree object when you have only the string ID or name, such as the document.getElementById( ) and, for older browsers, named indexes of the document.forms, document.images, and document.formRef.elements arrays.

Returned Value

Object reference.

Parameters

string
Any string representation of an object reference.

isFinite( )NN 4 IE 4 ECMA 1

isFinite(expression)

Returns a Boolean value of true if the number passed as a parameter is anything within the range of Number.MIN_VALUE and Number.MAX_VALUE, inclusive. String values passed as parameters cause the function to return false.

Returned Value

Boolean value: true | false.

Parameters

expression
Any JavaScript expression.

isNaN( )NN 2 IE 3 ECMA 1

isNaN(expression)

Returns a Boolean value of true if the expression passed as a parameter does not evaluate to a numeric value. Any expression that evaluates to NaN (such as performing parseInt( ) on a string that does not begin with a numeral) causes the isNaN( ) method to return true.

Returned Value

Boolean value: true | false.

Parameters

expression
Any JavaScript expression.

parseInt( )NN 2 IE 3 ECMA 1

parseInt("string "[, radix]) 

Returns an integer value (as a number data type in base-8 or base-10) of the numerals in the string passed as a parameter. The string value must at least begin with a numeral, or the result is NaN. If the string starts with numbers but changes to letters along the way or includes white space, only the leading numbers up to the first nonnumeral or whitespace are converted to the integer. Therefore, you can use the expression:

parseInt(navigator.appVersion)

to extract only the whole number of the version that leads the otherwise long string that is returned from that property.

The optional radix parameter lets you specify the base of the number being passed to the function. A number string that begins with zero is normally treated as an octal number, which gives you the wrong answer. It is a good idea to use the radix value of 10 on all parseInt( ) functions if all of your dealings are in base-10 numbers.

Returned Value

Integer.

Parameters

string
Any string that begins with one or more numerals.

radix
An integer of the number base of the number passed as the string parameter (e.g., 2, 8, 10, 16).

parseFloat( )NN 2 IE 3 ECMA 1

parseFloat(string)

Returns a number value (either an integer or floating-point number) of the numerals in the string passed as a parameter. The string value must at least begin with a numeral, or the result is NaN. If the string starts with numbers but changes to letters along the way, only the leading numbers are converted to the integer. Therefore, you can use the expression:

parseFloat(navigator.appVersion)

to extract the complete version number (e.g., 4.03) that leads the otherwise long string that is returned from that property.

If the converted value doesn't have any nonzero values to the right of the decimal, the returned value is an integer. Floating-point values are returned only when the number calls for it.

Returned Value

Number.

Parameters

string
Any string that begins with one or more numerals.

ScriptEngine( ), ScriptEngineBuildVersion( ), ScriptEngineMajorVersion( ), ScriptEngineMinorVersion( )NN n/a IE 4 ECMA n/a

These Internet Explorer-only functions reveal information about the scripting engine (JScript, VBScript, or VBA) being used to invoke the method and which version of that engine is installed. For JScript, the version refers to the version of the Jscript.dll file installed among the browser's support files. The major version is the part of the version number to the left of the version decimal point; the minor version is the part to the right of the decimal point. More granular than that is the internal build number that Microsoft uses to keep track of release generations during development and through release.

Returned Value

ScriptEngine( ) returns a string of one of the following engine names: JScript | VBA | VBScript. All other functions return integer values.

Parameters

None.

unescape( )NN 2 IE 3 ECMA |1|

unescape(string)

Returns a decoded version of the URL-encoded string passed as a parameter to the function. URL encoding converts nonalphanumeric characters (except * _ + - . / and, in IE, @) to hexadecimal values (such as %20 for the space character). Note that in IE 5.5 for Windows and Netscape 6, this method has been deprecated in favor of the decodeURI( ) and decodeURIComponent( ) methods. This method has been removed from the ECMA 3 specification.

Returned Value

String.

Parameters

string
Any URL-encoded string value.

unwatch( ), watch( )NN 4 IE n/a ECMA n/a

unwatch(property)
watch(property, funcHandler) 

These Navigator-specific functions are used primarily by JavaScript debuggers. When a statement invokes the watch( ) function for an object, the parameters include the property whose value is to be watched and the reference to the function to be invoked whenever the value of the property is changed by an assignment statement. To turn off the watch operation, invoke the unwatch( ) function for the particular property engaged earlier.

Returned Value

Nothing.

Parameters

property
The name of the object's property to be watched.

funcHandler
The name of the function (no parentheses) to be invoked whenever the watched property's value changes.

MathNN 2 IE 3 ECMA 1

The Math object is used only in its static object form as a library of math constant values and (mostly trigonometric) operations. As a result, there is no constructor function. Math object properties are constant values, while methods return a numeric value reflecting some math operation on a value; the original value is not altered when the method is invoked.

Invoking a Math object property or method adheres to the following syntax:

Math.propertyName
Math.method(param1[, param2])

Be sure to observe the uppercase "M" in the Math object in script statements. All expressions involving the Math object evaluate to or return a value.

Properties

E LN10 LN2 LOG10E LOG2E PI SQRT1_2 SQRT2

Methods

abs( )

acos( )

asin( )

atan( )

atan2( )

ceil( )

cos( )

exp( )

floor( )

log( )

max( )

min( )

pow( )

random( )

round( )

sin( )

sqrt( )

tan( )

ENN 2 IE 3 ECMA 1

Read-only
Returns Euler's constant.

Example

var num = Math.E;

Value

2.718281828459045

LN2NN 2 IE 3 ECMA 1

Read-only
Returns the natural logarithm of 2.

Example

var num = Math.LN2;

Value

0.6931471805599453

LN10NN 2 IE 3 ECMA 1

Read-only
Returns the natural logarithm of 10.

Example

var num = Math.LN10;

Value

2.302585092994046

LOG2ENN 2 IE 3 ECMA 1

Read-only
Returns the log base-2 of Euler's constant.

Example

var num = Math.LOG2E;

Value

1.4426950408889634

LOG10ENN 2 IE 3 ECMA 1

Read-only
Returns the log base-10 of Euler's constant.

Example

var num = Math.LOG10E;

Value

0.4342944819032518

PINN 2 IE 3 ECMA 1

Read-only
Returns the value of π.

Example

var num = Math.PI;

Value

3.141592653589793

SQRT1_2NN 2 IE 3 ECMA 1

Read-only
Returns the square root of 0.5.

Example

var num = Math.SQRT1_2;

Value

0.7071067811865476

SQRT2NN 2 IE 3 ECMA 1

Read-only
Returns the square root of 2.

Example

var num = Math.SQRT2;

Value

1.4142135623730951

abs( )NN 2 IE 3 ECMA 1

abs(number)

Returns the absolute value of the number passed as a parameter.

Returned Value

Positive number or zero.

Parameters

number
Any number.

acos( )NN 2 IE 3 ECMA 1

acos(number)

Returns the arc cosine (in radians) of the number passed as a parameter.

Returned Value

Number.

Parameters

number
Any number from -1 to 1.

asin( )NN 2 IE 3 ECMA 1

asin(number)

Returns the arc sine (in radians) of the number passed as a parameter.

Returned Value

Number.

Parameters

number
Any number from -1 to 1.

atan( )NN 2 IE 3 ECMA 1

atan(number)

Returns the arc tangent (in radians) of the number passed as a parameter.

Returned Value

Number.

Parameters

number
Any number between negative infinity and infinity.

atan2( )NN 2 IE 4 ECMA 1

atan2(x, y)

Returns the angle (in radians) of angle formed by a line to Cartesian point x, y.

Returned Value

Number between -π and π.

Parameters

x
Any number.

y
Any number.

ceil( )NN 2 IE 3 ECMA 1

ceil(number)

Returns the next higher integer that is greater than or equal to the number passed as a parameter.

Returned Value

Integer.

Parameters

number
Any number.

cos( )NN 2 IE 3 ECMA 1

cos(number)

Returns the cosine of the number passed as a parameter.

Returned Value

Number.

Parameters

number
Any number.

exp( )NN 2 IE 3 ECMA 1

exp(number)

Returns the value of Euler's constant to the power of the number passed as a parameter.

Returned Value

Number.

Parameters

number
Any number.

floor( )NN 2 IE 3 ECMA 1

floor(number)

Returns the next lower integer that is less than or equal to the number passed as a parameter.

Returned Value

Integer.

Parameters

number
Any number.

log( )NN 2 IE 3 ECMA 1

log(number)

Returns the natural logarithm (base e) of the number passed as a parameter.

Returned Value

Number.

Parameters

number
Any number.

max( )NN 2 IE 3 ECMA 1

max(number1, number2) 

Returns the greater value of the two parameters.

Returned Value

Number.

Parameters

number1
Any number.

number2
Any number.

min( )NN 2 IE 3 ECMA 1

min(number1, number2) 

Returns the lesser value of the two parameters.

Returned Value

Number.

Parameters

number1
Any number.

number2
Any number.

pow( )NN 2 IE 3 ECMA 1

pow(number1, number2) 

Returns the value of the first parameter raised to the power of the second parameter.

Returned Value

Number.

Parameters

number1
Any number.

number2
Any number.

random( )NN 2 IE 3 ECMA 1

Returns a pseudo-random number between 0 and 1. To calculate a pseudo-random integer between zero and another maximum value, use the formula:

Math.floor(Math.random( ) * n)

where n is the top integer of the acceptable range. To calculate a pseudo-random integer between a range starting with a number other than zero, use the formula:

Math.floor(Math.random( ) * n - m + 1) + m

where m is the lowest integer of the acceptable range and n equals the maximum value of the range. Note that the Math.random( ) method does not work in the Windows and Macintosh versions of Navigator 2.

Returned Value

Number from 0 up to, but not including, 1.

Parameters

None.

round( )NN 2 IE 3 ECMA 1

round(number)

Returns an integer that follows rounding rules. If the value of the passed parameter is greater than or equal to x.5, the returned value is x + 1; otherwise, the returned value is x.

Returned Value

Integer.

Parameters

number
Any number.

sin( )NN 2 IE 3 ECMA 1

sin(number)

Returns the sine (in radians) of the number passed as a parameter.

Returned Value

Number.

Parameters

number
Any number.

sqrt( )NN 2 IE 3 ECMA 1

sqrt(number)

Returns the square root of the number passed as a parameter.

Returned Value

Number.

Parameters

number
Any number.

tan( )NN 2 IE 3 ECMA 1

tan(number)

Returns the tangent (in radians) of the number passed as a parameter.

Returned Value

Number.

Parameters

number
Any number between negative infinity and infinity.

NumberNN 3 IE 4 ECMA 1

A Number object represents any numerical value, whether it is an integer or floating-point number. By and large, you don't have to worry about the Number object because a numerical value automatically becomes a Number object instance whenever you use such a value or assign it to a variable. On the other hand, you might want access to the static properties that only a math major would love.

Creating a Number Object

var myValue = number;
var myValue = new Number(number);

Properties

 
constructor MAX_VALUE MIN_VALUE NaN
NEGATIVE_INFINITY POSITIVE_INFINITY prototype  
   

Methods

 
         
toExponential( ) toFixed( ) toLocaleString( ) toPrecision( )
toString( ) valueOf( )    
constructorNN 4 IE 4 ECMA 1

Read/Write
This is a reference to the function that created the instance of a Number object—the native Number( ) constructor function in browsers.

Example

if (myVar.constructor == Number) {
    // process native function
}

Value

Function object reference.

MAX_VALUENN 3 IE 4 ECMA 1

Read-only
Equal to the highest possible number that JavaScript can handle.

Example

var tiptop = Number.MAX_VALUE;

Value

1.7976931348623157e+308

MIN_VALUENN 3 IE 4 ECMA 1

Read-only
Equal to the smallest possible number that JavaScript can handle.

Example

var itsybitsy = Number.MIN_VALUE;

Value

5e-324

NaNNN 3 IE 4 ECMA 1

Read-only
Equal to a value that is not-a-number. JavaScript returns this value when a numerical operation yields a non-numerical result because of a flaw in one of the operands. If you want to test whether a value is not a number, use the isNaN( ) global function rather than comparing to this property value.

Value

NaN

NEGATIVE_INFINITY, POSITIVE_INFINITYNN 3 IE 4 ECMA 1

Read-only
Values that are outside of the bounds of Number.MIN_VALUE and Number.MAX_VALUE, respectively.

Example

Number.NEGATIVE_INFINITY

Value

-Infinity; Infinity

prototypeNN 3 IE 4 ECMA 1

Read/Write
A property of the static Number object. Use the prototype property to assign new properties and methods to future instances of a Number value created in the current document. See the Array.prototype property description for examples. There is little need to create new prototype properties or methods for the Number object.

Example

Number.prototype.author = "DG";

Value

Any data, including function references.

toExponential( )NN 6 IE 5.5(Win) ECMA 3

toExponential(fractionDigits) 

Returns a string containing the number object's value displayed in JavaScript's exponential notation. The single parameter specifies the number of digits to the right of the decimal to display in the string. For example, if a variable contains the number 9876.54, if you apply the toExponential(10) method, the result is 9.8765400000E+3, with zeroes padding the rightmost digits to reach a total of 10 digits to the right of the decimal. If you specify a parameter that yields a display with fewer digits than in the original number, the returned value is rounded.

Returned Value

String.

Parameters

fractionDigits
An integer specifying the number of digits to the right of the decimal in the returned string.

toFixed( )NN 6 IE 5.5(Win) ECMA 3

toFixed(fractionDigits) 

Returns a string containing the number object's value displayed with a fixed number of digits to the right of the decimal (useful for currency calculation results). If you specify a parameter that yields a display with fewer significant digits than the original number, the returned value is rounded, but based only on the value of the digit immediately to the right of the last displayed digit (i.e., rounding does not cascade).

Returned Value

String.

Parameters

fractionDigits
An integer specifying the number of digits to the right of the decimal in the returned string.

toLocaleString( )NN 6 IE 5(Mac/5.5(Win) ECMA 3

Returns a string version of the number object's value. The precise format of the returned value is not mandated by the ECMA standard, and may be different from one local currency system to another (as set in the client computer's international preferences). On a U.S. English system, IE 5.5 and later for Windows returns a value with two digits to the right of the decimal (rounding values if necessary), with commas denoting thousands, millions, and so on. IE 5 for Macintosh does the same except for the commas. Netscape 6 performs no special formatting.

Returned Value

String.

Parameters

None.

toPrecision( )NN 6 IE 5.5(Win) ECMA 3

toPrecision(precisionDigits) 

Returns a string containing the number object's value displayed with a fixed number of digits, counting digits to the left and right of the decimal. If you specify a parameter that yields a display with fewer digits to the left of the decimal than the original number, the returned value is displayed in exponential notation. Truncated values are rounded, but based only on the value of the digit immediately to the right of the last displayed digit (i.e., rounding does not cascade).

Returned Value

String.

Parameters

precisionDigits
An integer specifying the total number of digits in the returned string.

toString( )NN 4 IE 4 ECMA 1

Returns the object's value as a string data type. You don't need this method in practice because the browsers automatically convert Number values to strings when they are needed for display in alert dialogs or in-document rendering.

Returned Value

String.

Parameters

None.

valueOf( )NN 4 IE 4 ECMA 1

Returns the object's value.

Returned Value

A numeric value.

Parameters

None.

ObjectNN 3 IE 4 ECMA 1

In addition to serving quietly as the foundation of all native JavaScript objects, the Object object is the pure model of the JavaScript object—including custom scripts objects you create. Use the Object object to generate things in your scripts with behaviors that are defined by custom properties and/or methods. Most typically, you start by creating a blank object with the constructor function and then assign values to new properties of that object.

Navigator 4 and later and IE 5 and later also let you assign properties and values via a special literal syntax that also creates the Object instance in the process:

var myObject = {propName1:propValue1[, propName2:propValue2[, 
...propNameN:propValueN]]}

You can use objects as data structures for structured custom data in your scripts, much like creating an array with named index values.

Creating an Object Object

var myObject = new Object( );
var myObject = {propName1:propVal1[, propName2:propVal2[,...N]]};
var myObject = new constructorFuncName([propVal1[, propVal2[,...N]]]);

Properties

constructor

prototype

Methods

hasOwnProperty( )

isPrototypeOf( )

propertyIsEnumerable( )

toLocaleString( )

toString( )

valueOf( )

constructorNN 4 IE 4 ECMA 1

Read/Write
Provides a reference to the function that created the instance of an Object object—the native Object( ) constructor function in browsers.

Example

if (myVar.constructor == Object) {
    // process native string
}

Value

Function object reference.

prototypeNN 4 IE 4 ECMA 1

Read/Write
This is a property of the static Object. Use the prototype property to assign new properties and methods to future instances of an Object created in the current document. See the Array.prototype property description for examples.

Example

Object.prototype.author = "DG";

Value

Any data, including function references.

hasOwnProperty( )NN 6 IE 5.5(Win) ECMA 3

hasOwnProperty("propertyName")

Returns Boolean true if, at the time the current object's instance was created, its constructor (or literal assignment) contained a property with a name that matches the parameter value. A property assigned to an object via its prototype property is not considered one of the object's own properties.

Returned Value

Boolean value: true | false.

Parameters

propertyName
String containing the name of an object property.

isPrototypeOf( )NN 6 IE 5.5(Win) ECMA 3

isPrototypeOf(objectReference)

Returns Boolean true if the current object and the object passed as a parameter coincide at some point along each object's prototype inheritance chain. Note that IE and Navigator do not always agree on the results.

Returned Value

Boolean value: true | false.

Parameters

objectReference
Reference to an object that potentially shares prototype inheritance with the current object.

propertyIsEnumerable( )NN 6 IE 5.5(Win) ECMA 3

propertyIsEnumerable("propertyName")

Returns Boolean true if the property, whose name is passed as a parameter, exposes itself to for/in property inspection through the object.

Returned Value

Boolean value: true | false.

Parameters

propertyName
String containing the name of an object property.

toLocaleString( )NN 6 IE 5.5(Win) ECMA 3

Browsers are free to determine how to localize string representations of object instances. For now, they appear to perform the same action as the toString( ) method, returning the value [object Object].

Returned Value

String.

Parameters

None.

toString( )NN 4 IE 4 ECMA 1

Returns the object's value as a string data type. In recent browsers, this value is [object Object].

Returned Value

String.

Parameters

None.

valueOf( )NN 4 IE 4 ECMA 1

Returns the object's value.

Returned Value

An object reference.

Parameters

None.

RegExpNN 4 IE 4 ECMA 3

The RegExp object is a static object that both generates instances of a regular expression and monitors all regular expression in the current window or frame. Instances of the RegExp object are covered in the regular expressions object description that follows this section.

Regular expressions assist in locating text that matches patterns of characters or characteristics. For example, a regular expression can be used to find out very quickly if an entry in a text field is a five-digit number. Defining the pattern to match requires knowledge of a separate notation syntax that is beyond the scope of this book (but is covered in Mastering Regular Expressions, by Jeffrey E. F. Friedl, published by O'Reilly). A summary of the syntax can be found in the description of the regular expression object.

Properties of the RegExp object store information about the last operation of any regular expression in the document. Therefore, it is conceivable that each property could change after each regular expression operation. Such operations include not only the methods of a regular expression object instance (exec( ) and test( )), but also the String object methods that accept regular expressions as parameters (match( ), replace( ), and split( )). Some of these properties are passed to the regular expression object as well, in preparation for the next operation with the regular expression.

All properties have verbose names as well as shortcut names that begin with $.

Properties

index

input

lastIndex

lastMatch

lastParen

leftContext

multiline

prototype

rightContext

$1

$2

$3

$4

$5

$6

$7

$8

$9

indexNN n/a IE 4 ECMA n/a

Read-only
This is the zero-based index value of the character position within the string where the most recent search for the pattern began. The lastIndex property provides the end position.

Example

var srchStart = RegExp.index;

Value

Integer.

inputNN 4 IE 4 ECMA n/a

Read/Write
This is the main string against which a regular expression is compared. If the main string is handed to the regular expression operation as a parameter to a method, this value is null. The short version is $_ (dollar sign, underscore).

Example

RegExp.input = "Four score and seven years ago...";

Value

String.

lastIndexNN n/a IE 4 ECMA n/a

Read/Write
This is the zero-based index value of the character within the string where the next search for the pattern begins. In a new search, the value is zero. You can also set the value manually if you wish to start at a different location or skip some characters. This property is echoed in the regular expression object instance, and is supported there in Navigator.

Example

myRE.lastIndex = 30;

Value

Integer.

lastMatchNN 4 IE 5(Mac)/5.5(Win) ECMA n/a

Read-only
Returns the string that matches the regular expression as a result of the most recent operation. The short version is $&.

Example

var matched = RegExp.lastMatch;

Value

String.

lastParenNN 4 IE 5(Mac)/5.5(Win) ECMA n/a

Read-only
Returns the string that matches the last parenthesized subcomponent of the regular expression as a result of the most recent operation. The short version is $+.

Example

var myValue = RegExp.lastParen;

Value

String.

leftContext, rightContextNN 4 IE 5(Mac)/5.5(Win) ECMA n/a

Read-only
The leftContext property returns the string starting with the beginning of the most recent searched text up to, but not including, the matching string. The rightContext property returns the string starting with the main string portion immediately following the matching string and extending to the end of the string. The short versions are $` and $', respectively. Because the start of subsequent searches on the same main string move inexorably toward the end of the main string, the starting point of the leftContext value can shift with each operation.

Example

var wholeContext = RegExp.leftContext + RegExp.lastMatch + RegExp.rightContext;

Value

String.

multilineNN 4 IE 5(Mac)/5.5(Win) ECMA 3

Read/Write
If the search extends across multiple lines of text, the multiline property is set to true. A search through text in a textarea element, for example, is multiline. The short version is $*.

Example

if (RegExp.multiline) {
    ...
}

Value

Boolean.

prototypeNN 4 IE 4 ECMA 3

Read/Write

See this property for the Array object.

$1, ..., $9NN 4 IE 4 ECMA n/a

Read-only
Parenthesized subcomponents of a regular expression return results. These results are stored individually in properties labeled 1 through 9, preceded by the $ shortcut symbol. The order is based on the position of the left parenthesis of a subcomponent: the leftmost subcomponent result is placed into $1. These properties may be used directly within parameters to String methods that use regular expressions (see the String.replace( ) method).

Example

RegExp.$2

Value

String.

regular expressionNN 4 IE 4 ECMA 3

A regular expression object is an instance of the RegExp object. Each regular expression object consists of a pattern that is used to locate matches within a string. Patterns for a regular expression can be simple strings or significantly more powerful expressions that use a notation that is essentially a language unto itself. The implementation of regular expressions in JavaScript 1.2 is very similar to the way they are implemented in Perl. You can read more about these concepts in books covering JavaScript 1.2 or later.

To create a regular expression object, surround the pattern with forward slashes, and assign the whole expression to a variable. For example, the following statement creates a regular expression with a pattern that is a simple word:

var re = /greet/;

The re variable can then be used as a parameter in a variety of methods that search for the pattern within some string (you may also use an expression directly as a method parameter, rather than assigning it to a variable).

Regular expression notation also consists of a number of metacharacters that stand in for sometimes complex ideas, such as the boundary on either side of a word, any numeral, or one or more characters. For example, to search for the pattern of characters shown above but only when the pattern is a word (and not part of a word such as greetings), the regular expression notation uses the metacharacters to indicate that the pattern includes word boundaries on both sides of the pattern:

var re = /\bgreet\b/;

The following table shows a summary of the regular expression notation used in JavaScript 1.2.

Character

Matches

Example

\b

Word boundary

/\bto/ matches "tomorrow"
/to\b/
matches "Soweto"
/\bto\b/ matches "to"

\B

Word nonboundary

/\Bto/ matches "stool" and "Soweto"
/to\B/
matches "stool" and "tomorrow"
/\Bto\B/ matches "stool"

\d

Numeral 0 through 9

/\d\d/ matches "42"

\D

Nonnumeral

/\D\D/ matches "to"

\s

Single whitespace

/under\sdog/ matches "under dog"

\S

Single nonwhitespace

/under\Sdog/ matches "under-dog"

\w

Letter, numeral, or underscore

/1\w/ matches "1A"

\W

Not a letter, numeral, or underscore

/1\W/ matches "1%"

.

Any character except a newline

/../ matches "Z3"

[...]

Any one of the character set in brackets

/J[aeiou]y/ matches "Joy"

[^...]

Negated character set

/J[^eiou]y/ matches "Jay"

*

Zero or more times

/\d*/ matches "", "5", or "444"

?

Zero or one time

/\d?/ matches "" or "5"

+

One or more times

/\d+/ matches "5" or "444"

{n}

Exactly n times

/\d{2}/ matches "55"

{n,}

n or more times

/\d{2,}/ matches "555"

{n,m}

At least n, at most m times

/\d{2,4}/ matches "5555"

^

At beginning of a string or line

/^Sally/ matches "Sally says..."

$

At end of a string or line

/Sally.$/ matches "Hi, Sally."

When you create a regular expression, you may optionally wire the expression to work globally (as you probably do if the regular expression is doing a search-and-replace operation with a method, and your goal is a "replace all" result) and to ignore case in its matches. The modifiers that turn on these switches are the letters g and i. They may be used by themselves or together as gi.

Once you have established a pattern with the regular expression notation, all the action takes place in the regular expression object methods and the String object methods that accept regular expression parameters.

Creating a regular expression Object

var regExpressionObj = /pattern/ [g | i | gi];
var regExpressionObj = new RegExp(["pattern", ["g" | "i" | "gi"]]);

Properties

constructor

global

ignoreCase

lastIndex

source

Methods

compile( )

exec( )

test( )

constructorNN 4 IE 4 ECMA 3

Read/Write

See this property for the Array object.

global, ignoreCaseNN 4 IE 5(Mac)/5.5(Win) ECMA 3

Read-only
Returns Boolean true if the regular expression object instance had the g or i modifiers (respectively) set when it was created. If a regular expression object has both modifiers set (gi), you must still test for each property individually.

Example

if (myRE.global && myRE.ignoreCase) {
    ...
}

Value

Boolean value: true | false.

lastIndexNN 4 IE 4 ECMA 3

Read/Write
This is the zero-based index value of the character within the string where the next search for the pattern begins. In a new search, the value is zero. You can also set the value manually if you wish to start at a different location or skip some characters.

Example

myRE.lastIndex = 30;

Value

Integer.

sourceNN 4 IE 4 ECMA 3

Read-only
Returns a string version of the characters used to create the regular expression. The value does not include the forward slash delimiters that surround the expression.

Example

var myREasString = myRE.source;

Value

String.

compile( )NN 4 IE 4 ECMA n/a

compile("pattern"[, "g" | "i" | "gi"])

Compiles a regular expression pattern into a genuine regular expression object. This method is used primarily to recompile a regular expression with a pattern that may change during the execution of a script.

Returned Value

Reference to a regular expression instance.

Parameters

pattern
Any regular expression pattern as a quoted string. Modifiers for global, ignore case, or both must be supplied as a separate quoted parameter.

exec( )NN 4 IE 4 ECMA 3

exec(string)

Performs a search through the string passed as a parameter for the current regular expression pattern. A typical sequence follows the format:

var myRE = /somePattern/;
var resultArray = myRE.exec("someString");

Properties of both the static RegExp and regular expression instance (myRE in the example) objects are updated with information about the results of the search. In addition, the exec( ) method returns an array of data, much of it similar to RegExp object properties. The returned array includes the following properties:

index
Zero-based index of starting character in the string that matches the pattern

input
The original string being searched

[0]
String of the characters matching the pattern

[1]...[n]
Strings of the results of the parenthesized component matches

You can stow away the results of the exec( ) method in a variable, whereas the RegExp property values change with the next regular expression operation. If the regular expression is set for global searching, a subsequent call to myRE.exec("someString") continues the search from the position of the previous match.

If no match is found for a given call to exec( ), it returns null.

Returned Value

An array of match information if successful; null if there is no match.

Parameters

string
The string to be searched.

test( )NN 4 IE 4 ECMA 3

test(string)

Returns Boolean true if there is a match of the regular expression anywhere in the string passed as a parameter, false if not. No additional information is available about the results of the search. This is the fastest way to find out if a string contains a match for a pattern.

Returned Value

Boolean value: true | false.

Parameters

string
The string to be searched.

StringNN 2 IE 3 ECMA 1

A String object represents any sequence of zero or more characters that are to be treated strictly as text (that is, no math operations are to be applied). A large library of methods is divided into two categories. One category surrounds a string with a pair of HTML tags for a variety of HTML character formatting. These methods are used primarily to assist statements that use document.write( ) to dynamically create content, but their functionality is now superceded by style sheets. The second, vital method category is the more traditional set of string parsing and manipulation methods that facilitate finding and copying characters and substrings, case changes, and conversion from string lists to JavaScript arrays.

By and large, you don't have to worry about explicitly creating a string beyond a simple assignment of a quoted string value:

var myString = "howdy";

Occasionally, however, it is helpful to create a string object using the constructor of the static String object. Preparing string values for passage to Java applets often requires this type of string generation:

var myString = new String("howdy");

Other than the constructor, prototype property, and fromCharCode( ) method, all properties and methods are for use with instances of the String object, rather than the static String object.

Creating a String Object

var myValue = "someString";
var myValue = new String("someString");

Properties

constructor

length

prototype

Methods

 

anchor( )

big( )

blink( )

bold( )

charAt( )

charCodeAt( )

concat( )

fixed( )

fontcolor( )

fontsize( )

fromCharCode( )

indexOf( )

italics( )

lastIndexOf( )

link( )

localeCompare( )

match( )

replace( )

search( )

slice( )

small( )

split( )

strike( )

sub( )

substr( )

substring( )

sup( )

toLocaleLowerCase( )

toLocaleUpperCase( )

toLowerCase( )

toString( )

toUpperCase( )

valueOf( )

     
 
constructorNN 4 IE 4 ECMA 1

Read/Write
This is a reference to the function that created the instance of a String object—the native String( ) constructor function in browsers.

Example

if (myVar.constructor == String) {
    // process native string
}

Value

Function object reference.

lengthNN 2 IE 3 ECMA 1

Read-only
Provides a count of the number of characters in the string. String values dynamically change their lengths if new values are assigned to them or if other strings are concatenated.

Example

for (var i = 0; i < myString.length; i++) {
    ...
}

Value

Integer.

prototypeNN 3 IE 4 ECMA 1

Read/Write
This is a property of the static String object. Use the prototype property to assign new properties and methods to future instances of a String value created in the current document. See the Array.prototype property description for examples.

Example

String.prototype.author = "DG";

Value

Any data, including function references.

anchor( )NN 2 IE 3 ECMA n/a

anchor("anchorName")

Returns a copy of the string embedded within an anchor (<a>) tag set. The value passed as a parameter is assigned to the name attribute of the tag.

Returned Value

A string within an a element.

Parameters

anchorName
A string to use as the value of the name attribute.

big( )NN 2 IE 3 ECMA n/a

Returns a copy of the string embedded within a <big> tag set.

Returned Value

A string within a big element.

Parameters

None.

blink( )NN 2 IE 3 ECMA n/a

Returns a copy of the string embedded within a <blink> tag set.

Returned Value

A string within a blink element.

Parameters

None.

bold( )NN 2 IE 3 ECMA n/a

Returns a copy of the string embedded within a <b> tag set.

Returned Value

A string within a b element.

Parameters

None.

charAt( )NN 2 IE 3 ECMA 1

charAt(positionIndex)

Returns a single character string of the character located at the zero-based index position passed as a parameter. Use this method instead of substring( ) when only one character from a known position is needed from a string.

Returned Value

A one-character string. In newer browser versions, an empty string is returned if the parameter value points to a character beyond the length of the string.

Parameters

positionIndex
Zero-based integer.

charCodeAt( )NN 4 IE 4 ECMA 1

charCodeAt(positionIndex)

Returns a number of the decimal Unicode value for the character located at the zero-based index position passed as a parameter. For common alphanumeric characters, the Unicode values are the same as ASCII values.

Returned Value

A positive integer. Returns NaN if the parameter value points to a character beyond the length of the string.

Parameters

positionIndex
Zero-based integer.

concat( )NN 4 IE 4 ECMA n/a

concat(string2)

Returns a string that appends the parameter string to the current string object. The results of this method are the same as concatenating strings with the add (+) or add-by-value (+=) operators. Neither the method nor operators insert spaces between the two string components.

Returned Value

String.

Parameters

string2
Any string.

fixed( )NN 2 IE 3 ECMA n/a

Returns a copy of the string embedded within a <tt> tag set.

Returned Value

A string within a tt element.

Parameters

None.

fontcolor( )NN 2 IE 3 ECMA n/a

fontColor(color)

Returns a copy of the string embedded within a font (<font>) tag set. The value passed as a parameter is assigned to the color attribute of the tag.

Returned Value

A string within a font element.

Parameters

color
A string to use as the value of the color attribute.

fontsize( )NN 2 IE 3 ECMA n/a

fontSize(size)

Returns a copy of the string embedded within a font (<font>) tag set. The value passed as a parameter is assigned to the size attribute of the tag.

Returned Value

A string within a font element.

Parameters

size
An integer to use as the value of the size attribute.

fromCharCode( )NN 4 IE 4 ECMA 1

fromCharCode(num1, [, num2,[...numN]]) 

This is a static method that returns a string of one or more characters with Unicode values that are passed as a comma-delimited list of parameters. For example, the expression:

String.fromCharCode(120, 121, 122)

returns "xyz".

Returned Value

A string.

Parameters

num1...numN
One or more integer values in an unquoted, comma-delimited list.

indexOf( )NN 2 IE 3 ECMA 1

indexOf(searchString[, startPositionIndex]) 

Returns a zero-based integer of the position within the current string where the searchString parameter starts. Normally, the search starts with the first (index of zero) character, but you may have the search begin later in the string by specifying the optional second parameter, which is the index value of where the search should start. If there is no match, the returned value is -1. This is a backward-compatible quick way to find out if one string contains another: if the returned value is -1 then you know the searchString is not in the larger string. If the returned value is another number (the precise value doesn't matter), the searchString is in the larger string. For browsers that support regular expressions, the String object's search( ) method performs a similar function.

Returned Value

Integer.

Parameters

searchString
A string to look for in the current string object.

startPositionIndex
A zero-based integer indicating the position within the current string object to begin the search of the first parameter.

italics( )NN 2 IE 3 ECMA n/a

Returns a copy of the string embedded within an <i> tag set.

Returned Value

A string within an i element.

Parameters

None.

lastIndexOf( )NN 2 IE 3 ECMA 1

lastIndexOf(searchString[, startPositionIndex]) 

Returns a zero-based integer of the position within the current string object where the searchString parameter starts. This method works like the indexOf( ) method but begins all searches from the end of the string or some index position. Even though searching starts from the end of the string, the startPositionIndex parameter is based on the start of the string, as is the returned value. If there is no match, the returned value is -1.

Returned Value

Integer.

Parameters

searchString
A string to look for in the current string object.

startPositionIndex
A zero-based integer indicating the position within the current string object to begin the search of the first parameter. Even though the search starts from the end of the string, this parameter value is relative to the front of the string.

link( )NN 2 IE 3 ECMA n/a

link(URL)

Returns a copy of the string embedded within an anchor (<a>) tag set. The value passed as a parameter is assigned to the href attribute of the tag.

Returned Value

A string within an a element.

Parameters

URL
A string to use as the value of the href attribute.

localeCompare( )NN 6 IE 5.5(Win) ECMA 3

localeCompare(string2)

Returns a number indicating whether the current string sorts before, the same as, or after the parameter string, based on browser- and system-dependent string localization. If the current string sorts before the parameter string, the return value is a negative number; if they are the same, the return value is 0, if the current string sorts after the parameter string, the return value is a positive number.

Use this method with caution if the strings contain characters outside the Latin character set because each browser can determine what localization equalities are in place. They also calculate the return values differently.

Returned Value

Integer

Parameters

string2
Any string.

match( )NN 4 IE 4 ECMA 3

match(regexpression)

Returns an array of strings within the current string that match the regular expression passed as a parameter. For example, if you pass a regular expression that specifies any five-digit number, the returned value of the match( ) method would be an array of all five-digit numbers (as strings) in the main string. Properties of the RegExp static object are influenced by this method's operation.

Returned Value

An array of strings.

Parameters

regexpression
A regular expression object. See the regular expression object for the syntax to create a regular expression object.

replace( )NN 4 IE 4 ECMA 3

replace(regexpression, replaceString) 

Returns the new string that results when matches of the regexpression parameter are replaced by the replaceString parameter. The original string is unharmed in the process, so you need to capture the returned value in a variable to preserve the changes.

Returned Value

A string.

Parameters

regexpression
A regular expression object. If you want the replace( ) method to act globally on the string, set the global switch (g) on the regular expression. See the regular expression object for the syntax to create a regular expression object.

replaceString
A string that is to take the place of all matches of regexpression in the current string.

search( )NN 4 IE 4 ECMA 3

search(regexpression)

Returns the zero-based indexed value of the first character in the current string that matches the pattern of the regexpression parameter. This method is similar to the indexOf( ) method, but the search is performed with a regular expression rather than a straight string.

Returned Value

Integer.

Parameters

regexpression
A regular expression object. See the regular expression object for the syntax to create a regular expression object.

slice( )NN 4 IE 4 ECMA 3

slice(startPositionIndex, endPositionIndex]) 

Returns a substring of the current string. The substring is copied from the main string starting at the zero-based index count value of the character in the main string. If no second parameter is provided, the substring extends to the end of the main string. The optional second parameter can be another zero-based index value of where the substring should end. This value may also be a negative value, which counts from the end of the string toward the front.

Returned Value

String.

Parameters

startPositionIndex
A zero-based integer indicating the position within the current string object to start copying characters.

endPositionIndex
A zero-based integer indicating the position within the current string object to end copying characters. Negative values count inward from the end of the string.

small( )NN 2 IE 3 ECMA n/a

Returns a copy of the string embedded within a <small> tag set.

Returned Value

A string within a small element.

Parameters

None.

split( )NN 3 IE 4 ECMA 1

split(delimiter [, limitInteger]) 

Returns a new array object whose elements are segments of the current string. The current string is divided into array entries at each instance of the delimiter string specified as the first parameter of the method. The delimiter does not become part of the array. You do not have to declare the array prior to stuffing the results of the split( ) method. For example, if a string consists of a comma-delimited list of names, you can convert the list into an array as follows:

var listArray = stringList.split(",");

You may also use a regular expression as the parameter to divide the string by a pattern rather than a fixed character.

Returned Value

Array.

Parameters

delimiter
A string or regular expression that defines where the main string is divided into elements of the resulting array.

limitInteger
An optional integer that restricts the number of items converted into array elements.

strike( )NN 2 IE 3 ECMA n/a

Returns a copy of the string embedded within a <strike> tag set.

Returned Value

A string within a strike element.

Parameters

None.

sub( )NN 2 IE 3 ECMA n/a

Returns a copy of the string embedded within a <sub> tag set.

Returned Value

A string within a sub element.

Parameters

None.

substr( )NN 4 IE 4 ECMA n/a

substr(startPositionIndex [, length]) 

Returns a copy of an extract from the current string. The extract begins at the zero-based index position of the current string as specified by the first parameter of the method. If no other parameter is provided, the extract continues to the end of the main string. The second parameter can specify an integer of the number of characters to be extracted from the main string. In contrast, the substring( ) method's parameters point to the start and end position index values of the main string.

Returned Value

A string.

Parameters

startPositionIndex
A zero-based integer indicating the position within the current string object to start copying characters

length
An optional integer of the number of characters to extract, starting with the character indicated by the startPositionIndex parameter

substring( )NN 2 IE 3 ECMA 1

substring(startPositionIndex, endPositionIndex) 

Returns a copy of an extract from the current string. The extract begins at the zero-based index position of the current string as specified by the first parameter of the method and ends just before the character whose index is specified by the second parameter. For example, "Frobnitz".substring(0,4) returns the substring from positions 0 through 3: Frob. In contrast, the substr( ) method's parameters point to the start position of the main string and the number of characters (length) to extract.

Returned Value

A string.

Parameters

startPositionIndex
A zero-based integer indicating the position within the current string object to start copying characters.

endPositionIndex
A zero-based integer indicating the position within the current string object to end copying characters. In other words, the copy is made from startPositionIndex up to, but not including, the character at position endPositionIndex.

sup( )NN 2 IE 3 ECMA n/a

Returns a copy of the string embedded within a <sup> tag set.

Returned Value

A string within a sup element.

Parameters

None.

toLocaleLowerCase( ), toLocaleUpperCase( )NN 6 IE 5.5 ECMA 3

Return a copy of the current string in all lowercase or uppercase letters. Works the same as the regular version, except for some non-Latin alphabets with character mappings that may require special internal handling.

Returned Value

String.

Parameters

None.

toLowerCase( ), toUpperCase( )NN 2 IE 3 ECMA 1

Return a copy of the current string in all lowercase or uppercase letters. If you want to replace the current string with a case-adjusted version, assign the result of the method to the same string:

myString = myString.toUpperCase( );

It is common to use either one of these methods to create a case-insensitive comparison of two strings. This is especially convenient if one of the strings being compared is entered by a user, who may submit a variety of case situations:

if (document.forms[0].entry.value.toLowerCase( ) == compareValue) {
    ...
}

Returned Value

String.

Parameters

None.

toString( ), valueOf( )NN 4 IE 4 ECMA 1

Return a string value of the object.

Returned Value

String value.

Parameters

None.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.