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


Book HomeMac OS X for Unix GeeksSearch this book

Chapter 23. Core JavaScript Reference

This part of the book is a reference section that documents the classes, methods, and properties defined by the core JavaScript language. The introduction and sample reference page explain how to use and get the most out of this reference section. Take the time to read this material carefully, and you will find it easier to locate and use the information you need!

This reference section is arranged alphabetically. The reference pages for the methods and properties of classes are alphabetized by their full names, which include the names of the classes that define them. For example, if you want to read about the replace( ) method of the String class, you would look under "String.replace," not just "replace."

Core JavaScript defines some global functions and properties, such as eval( ) and NaN. Technically, these are properties of a global object. Since the global object has no name, however, they are listed in this reference section under their own unqualified names. For convenience, the full set of global functions and properties in core JavaScript is summarized in a special reference page named "Global" (even though there is no object or class by that name).

Sometimes you may find that you don't know the name of the class or interface that defines the method or property want to look up, or you may not be sure which of the three reference sections to look up a class or interface in. Part VI of this book is a special index designed to help with these situations. Look up the name of a class, method, or property, and it will tell you which reference section to look in and which class to look under in that section. For example, if you look up "Date," it will tell you that the Date class is documented in this core reference section. And if you look up the name "match," it will tell you that match( ) is a method of the String class and is also documented in this section.

Once you've found the reference page you're looking for, you shouldn't have much difficulty finding the information you need. Still, you'll be able to make better use of this reference section if you understand how the reference pages are written and organized. What follows is a sample reference page titled "Sample Entry" that demonstrates the structure of each reference page and tells you where to find various types of information within the pages. Take the time to read this page before diving into the rest of the reference material.

Sample Entryhow to read core JavaScript reference pages

Title and Short Description

Every reference entry begins with a title block like that above. The entries are alphabetized by title. The short description, shown next to the title, gives you a quick summary of the item documented in the entry; it can help you quickly decide if you're interested in reading the rest of the page.

Availability

This information tells you which version of Netscape's JavaScript interpreter and Microsoft's JScript interpreter the item (class, method, or property) was introduced in. If the item has been standardized in ECMAScript, it tells you which version of the standard introduced it. You can assume that anything available in one version of JavaScript is also available in later versions. Note, however, that if this section says the item is deprecated it may be removed in the future and you should avoid using it.

Inherits from/Overrides

If a class inherits from a superclass or a method overrides a method in a superclass, that information is shown in the "Inherits from/Overrides" section.

As described in Chapter 8, JavaScript classes can inherit properties and methods from other classes. For example, the String class inherits from Object, and the RangeError class inherits from Error, which in turn inherits from Object. When you see this inheritance information, you may also want to look up the listed superclasses.

When a method has the same name as a method in a superclass, the method overrides the superclass's method. See Array.toString( ) for an example.

Constructor

If the reference page documents a class, it usually has a "Constructor" section that shows you how to use the constructor method to create instances of the class. Since constructors are a type of method, the "Constructor" section looks a lot like the "Synopsis" section of a method's reference page.

Synopsis

Reference pages for functions, methods, and properties have a "Synopsis" section that shows how you might use the function, method, or property in your code. For example, the synopsis for the Array.concat( ) method is:

array.concat(value, ...) 

The italic font indicates text that is to be replaced with something else. array should be replaced with a variable or JavaScript expression that holds or evaluates to an array. And value simply represents an arbitrary value that is to be concatenated to the array. The ellipsis (...) indicates that this method can take any number of value arguments. Because the terms concat and the open and close parentheses are not in italics, you must include them exactly as shown in your JavaScript code.

Arguments

If a reference page documents a function, a method, or a class with a constructor method, the "Constructor" or "Synopsis" section is followed by an "Arguments" subsection that describes the arguments to the method, function, or constructor. If there are no arguments, this subsection is simply omitted.

arg1
The arguments are described in a list here. This is the description for argument arg1, for example.

arg2
And this is the description for argument arg2.

Returns

If a constructor, function, or method has a return value, this subsection explains that value.

Throws

If a constructor, function, or method can throw an exception, this subsection lists the types of exceptions that may be thrown and explains the circumstances under which this can occur.

Properties

If the reference page documents a class, the "Properties" section lists the properties defined by the class and provides short explanations of each. In this core reference section, each property also has a complete reference page of its own. For example, the reference page for the Array class lists the length property in this section and gives a brief explanation of it, but the property is fully documented in the "Array.length" reference page. The property listing looks like this:

prop1
This is a summary of property prop1, including its type, its purpose or meaning, and whether it is read-only or read/write.

prop2
This is the same for prop2.

Methods

The reference page for a class that defines methods includes a "Methods" section. It is just like the "Properties" section, except that it summarizes methods instead of properties. All methods also have reference pages of their own.

Description

Most reference pages contain a "Description" section, which is the basic description of the class, method, function, or property that is being documented. This is the heart of the reference page. If you are learning about a class, method, or property for the first time, you may want to skip directly to this section and then go back and look at previous sections such as "Arguments," "Properties," and "Methods." If you are already familiar with a class, method, or property, you probably won't need to read this section and instead will just want to quickly look up some specific bit of information (for example, from the "Arguments" or "Properties" sections).

In some entries, this section is no more than a short paragraph. In others, it may occupy a page or more. For some simple methods, the "Arguments" and "Returns" sections document the method sufficiently by themselves, so the "Description" section is omitted.

Example

Some pages include an example that shows typical usage. Most pages do not contain examples, however -- you'll find those in first half of this book.

Bugs

When an item doesn't work quite right, this section describes the bugs. Note, however, that this book does not attempt to catalog every bug in every version and implementation of JavaScript.

See Also

Many reference pages conclude with cross-references to related reference pages that may be of interest. Sometimes reference pages also refer back to one of the main chapters of the book.

Argumentsarguments and other properties of a function

Availability

JavaScript 1.1; JScript 2.0; ECMAScript v1

Inherits from/Overrides

Inherits from Object

Synopsis

arguments
arguments[n]

Elements

The Arguments object is defined only within a function body. Although it is not technically an array, the Arguments object has numbered properties that function as array elements and a length property that specifies the number of array elements. Its elements are the values that were passed as arguments to the function. Element 0 is the first argument, element 1 is the second argument, and so on. All values passed as arguments become array elements of the Arguments object, whether or not those arguments are given names in the function declaration.

Properties

callee
A reference to the function that is currently executing.

length
The number of arguments passed to the function and the number of array elements in the Arguments object.

Description

When a function is invoked, an Arguments object is created for it and the local variable arguments is automatically initialized to refer to that Arguments object. The main purpose of the Arguments object is to provide a way to determine how many arguments were passed to the function and to refer to unnamed arguments. In addition to the array elements and length property, however, the callee property allows an unnamed function to refer to itself.

For most purposes, the Arguments object can be thought of as an array with the addition of the callee property. However, it is not an instance of Array, and the Arguments.length property does not have any of the special behaviors of the Array.length property and cannot be used to change the size of the array.

The Arguments object has one very unusual feature. When a function has named arguments, the array elements of the Arguments object are synonyms for the local variables that hold the function arguments. The Arguments object and the argument names provide two different ways of referring to the same variable. Changing the value of an argument with an argument name changes the value that is retrieved through the Arguments object, and changing the value of an argument through the Arguments object changes the value that is retrieved by the argument name.

See Also

Function; Chapter 7

Arguments.lengththe number of arguments passed to a function

Availability

JavaScript 1.1; JScript 2; ECMAScript v1

Synopsis

arguments.length

Description

The length property of the Arguments object specifies the number of arguments passed to the current function. This property is defined only within a function body.

Note that this property specifies the number of arguments actually passed, not the number expected. See Function.length for the number of declared arguments. Note also that this property does not have any of the special behavior of the Array.length property.

Example

// Use an Arguments object to check that correct # of args were passed
function check(args) {
    var actual = args.length;           // The actual number of arguments
    var expected = args.callee.length;  // The expected number of arguments
    if (actual != expected) {           // Throw exception if they don't match
        throw new Error("Wrong number of arguments: expected: " +
                         expected + "; actually passed " + actual);
    }
}
// A function that demonstrates how to use the function above
function f(x, y, z) {
    check(arguments);  // Check for correct number of arguments
    return x + y + z;  // Now do the rest of the function normally
}

See Also

Array.length, Function.length

Arraybuilt-in support for arrays

Availability

JavaScript 1.1; JScript 2.0; ECMAScript v1

Inherits from/Overrides

Inherits from Object

Constructor

new Array( )
new Array(size)
new Array(element0, element1, ..., elementn)

Arguments

size
The desired number of elements in the array. The returned array has its length field set to size.

element0, ... elementn
An argument list of two or more arbitrary values. When the Array( ) constructor is invoked with these arguments, the newly created array is initialized with the specified argument values as its elements and its length field set to the number of arguments.

Returns

The newly created and initialized array. When Array( ) is invoked with no arguments, the returned array is empty and has a length field of 0. When invoked with a single numeric argument, the constructor returns an array with the specified number of undefined elements. When invoked with any other arguments, the constructor initializes the array with the values specified by the arguments. When the Array( ) constructor is called as a function, without the new operator, it behaves exactly as it does when called with the new operator.

Throws

RangeError
When a single integer size argument is passed to the Array( ) constructor, a RangeError exception is thrown if size is negative or is larger than 232 -1.

Literal Syntax

ECMAScript v3 specifies and JavaScript 1.2 and JScript 3.0 implement an array literal syntax. You may also create and initialize an array by placing a comma-separated list of expressions within square brackets. The values of these expressions become the elements of the array. For example:

var a = [1, true, 'abc'];
var b = [a[0], a[0]*2, f(x)]; 

Properties

length
A read/write integer specifying the number of elements in the array or, when the array does not have contiguous elements, a number one larger than the index of the last element in the array. Changing the value of this property truncates or extends the array.

Methods

concat( )
Concatenates elements to an array.

join( )
Converts all array elements to strings and concatenate them.

pop( )
Removes an item from the end of an array.

push( )
Pushes an item onto the end of an array.

reverse( )
Reverses, in place, the order of the elements of an array.

shift( )
Shifts an element off the beginning of an array.

slice( )
Returns a subarray slice of an array.

sort( )
Sorts, in place, the elements of an array.

splice( )
Inserts, deletes, or replaces array elements.

toLocaleString( )
Converts an array to a localized string.

toString( )
Converts an array to a string.

unshift( )
Inserts elements at the beginning of an array.

Description

Arrays are a basic feature of JavaScript and are documented in detail in Chapter 9.

See Also

Chapter 9

Array.sort( )sort the elements of an array

Availability

JavaScript 1.1; JScript 2.0; ECMAScript v1

Synopsis

array.sort( ) array.sort(orderfunc)

Arguments

orderfunc
An optional function used to specify the sorting order.

Returns

A reference to the array. Note that the array is sorted in place and no copy is made.

Description

The sort( ) method sorts the elements of array in place -- no copy of the array is made. If sort( ) is called with no arguments, the elements of the array are arranged in alphabetical order (more precisely, the order determined by the character encoding). To do this, elements are first converted to strings, if necessary, so that they can be compared.

If you want to sort the array elements in some other order, you must supply a comparison function that compares two values and returns a number indicating their relative order. The comparison function should take two arguments, a and b, and should return one of the following:

  • A value less than zero, if, according to your sort criteria, a is "less than" b and should appear before b in the sorted array.

  • Zero, if a and b are equivalent for the purposes of this sort.

  • A value greater than zero, if a is "greater than" b for the purposes of the sort.

Note that undefined elements of an array are always sorted to the end of the array. This is true even if you provide a custom ordering function: undefined values are never passed to the orderfunc you supply.

Example

The following code shows how you might write a comparison function to sort an array of numbers in numerical, rather than alphabetical order:

// An ordering function for a numerical sort
function numberorder(a, b) { return a - b; }

a = new Array(33, 4, 1111, 222);
a.sort( );             // Alphabetical sort: 1111, 222, 33, 4
a.sort(numberorder);    // Numerical sort: 4, 33, 222, 1111
Array.splice( ) insert, remove, or replace array elements

Availability

JavaScript 1.2; JScript 5.5; ECMAScript v3

Synopsis

array.splice(start, deleteCount, value, ...)

Arguments

start
The array element at which the insertion and/or deletion is to begin.

deleteCount
The number of elements, starting with and including start, to be deleted from array. This argument is optional; if not specified, splice( ) deletes all elements from start to the end of the array.

value, ...
Zero or more values to be inserted into array, beginning at the index specified by start.

Returns

An array containing the elements, if any, deleted from array. Note, however, that due to a bug, the return value is not always an array in the Netscape implementation of JavaScript 1.2.

Description

splice( ) deletes zero or more array elements starting with and including the element start and replaces them with zero or more values specified in the argument list. Array elements that appear after the insertion or deletion are moved as necessary so that they remain contiguous with the rest of the array. Note that, unlike the similarly named slice( ), splice( ) modifies array directly.

Example

The operation of splice( ) is most easily understood through an example:

var a = [1,2,3,4,5,6,7,8]
a.splice(4);        // Returns [5,6,7,8]; a is [1,2,3,4]
a.splice(1,2);      // Returns [2,3]; a is [1,4]
a.splice(1,1);      // Netscape/JavaScript 1.2 returns 4 instead of [4]
a.splice(1,0,2,3);  // Netscape/JavaScript 1.2 returns undefined instead of []

Bugs

splice( ) is supposed to return an array of deleted elements in all cases. However, in Netscape's JavaScript 1.2 interpreter, when a single element is deleted it returns that element rather than an array containing the element. Also, if no elements are deleted, it returns nothing instead of returning an empty array. Netscape implementions of JavaScript emulate this buggy behavior whenever Version 1.2 of the language is explicitly specified.

See Also

Array.slice( )

Booleansupport for boolean values

Availability

JavaScript 1.1; JScript 2.0; ECMAScript v1

Inherits from/Overrides

Inherits from Object

Constructor

new Boolean(value) //Constructor function
Boolean(value) // Conversion function

Arguments

value
The value to be held by the Boolean object or to be converted to a boolean value.

Returns

When invoked as a constructor with the new operator, Boolean( ) converts its argument to a boolean value and returns a Boolean object that contains that value. When invoked as a function, without the new operator, Boolean( ) simply converts its argument to a primitive boolean value and returns that value.

The values 0, NaN, null, the empty string "", and the undefined value are all converted to false. All other primitive values, except false (but including the string "false"), and all objects and arrays are converted to true.

Methods

toString( )
Returns true or false, depending on the boolean value represented by the Boolean object.

valueOf( )
Returns the primitive boolean value contained in the Boolean object.

Description

Boolean values are a fundamental data type in JavaScript. The Boolean object is an object wrapper around the boolean value. This Boolean object type exists primarily to provide a toString( ) method to convert boolean values to strings. When the toString( ) method is invoked to convert a boolean value to a string (and it is often invoked implicitly by JavaScript) JavaScript internally converts the boolean value to a transient Boolean object, on which the method can be invoked.

See Also

Object

Datemanipulate dates and times

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Inherits from/Overrides

Inherits from Object

Constructor

new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year, month, day, hours, minutes, seconds, ms)

With no arguments, the Date( ) constructor creates a Date object set to the current date and time. When one numeric argument is passed, it is taken as the internal numeric representation of the date in milliseconds, as returned by the getTime( ) method. When one string argument is passed, it is a string representation of a date, in the format accepted by the Date.parse( ) method. Otherwise, the constructor is passed between two and seven numeric arguments that specify the individual fields of the date and time. All but the first two arguments -- the year and month fields -- are optional. Note that these date and time fields are specified using local time, not UTC (similar to GMT) time. See the static Date.UTC( ) method for an alternative.

Date( ) may also be called as a function, without the new operator. When invoked in this way, Date( ) ignores any arguments passed to it and returns a string representation of the current date and time.

Arguments

milliseconds
The number of milliseconds between the desired date and midnight on January 1, 1970 (UTC). For example, passing the argument 5000 would create a date that represents five seconds past midnight on 1/1/70.

datestring
A single argument that specifies the date and, optionally, the time as a String. The string should be in a format accepted by Date.parse( ).

year
The year, in four-digit format. For example, specify 2001 for the year 2001. For compatibility with early implementations of JavaScript, if this argument is between 0 and 99, 1900 is added to it.

month
The month, specified as an integer from 0 ( January) to 11 (December).

day
The day of the month, specified as an integer from 1 to 31. Note that this argument uses 1 as its lowest value, while other arguments use 0 as their lowest value. Optional.

hours
The hour, specified as an integer from 0 (midnight) to 23 (11 p.m.). Optional.

minutes
The minutes in the hour, specified as an integer from 0 to 59. Optional.

seconds
The seconds in the minute, specified as an integer from 0 to 59. Optional.

ms
The milliseconds in the second, specified as an integer from 0 to 999. Optional.

Methods

The Date object has no properties that can be read and written directly; instead, all access to date and time values is done through methods. Most methods of the Date object come in two forms: one that operates using local time, and one that operates using universal (UTC or GMT) time. If a method has "UTC" in its name, it operates using universal time. These pairs of methods are listed together below. For example, the listing for get[UTC]Day( ) refers to both the methods getDay( ) and getUTCDay( ).

Date methods may be invoked only on Date objects and throw a TypeError exception if you attempt to invoke them on any other type of object.

get[UTC]Date( )
Returns the day of the month of a Date object, in local or universal time.

get[UTC]Day( )
Returns the day of the week of a Date object, in local or universal time.

get[UTC]FullYear( )
Returns the year of the date in full four-digit form, in local or universal time.

get[UTC]Hours( )
Returns the hours field of a Date object, in local or universal time.

get[UTC]Milliseconds( )
Returns the milliseconds field of a Date object, in local or universal time.

get[UTC]Minutes( )
Returns the minutes field of a Date object, in local or universal time.

get[UTC]Month( )
Returns the month field of a Date object, in local or universal time.

get[UTC]Seconds( )
Returns the seconds field of a Date object, in local or universal time.

getTime( )
Returns the internal, millisecond representation of a Date object. Note that this value is independent of time zone, and therefore, there is not a separate getUTCTime( ) method.

getTimezoneOffset( )
Returns the difference, in minutes, between the local and UTC representations of this date. Note that the value returned depends on whether daylight savings time is or would be in effect at the specified date.

getYear( )
Returns the year field of a Date object. Deprecated in favor of getFullYear( ).

set[UTC]Date( )
Sets the day of the month field of the date, using local or universal time.

set[UTC]FullYear( )
Sets the year (and optionally month and day) of the date, using local or universal time.

set[UTC]Hours( )
Sets the hour (and optionally the minutes, seconds, and milliseconds fields) of the date, using local or universal time.

set[UTC]Milliseconds( )
Sets the milliseconds field of a date, using local or universal time.

set[UTC]Minutes( )
Sets the minutes field (and optionally the seconds and milliseconds fields) of a date, using local or universal time.

set[UTC]Month( )
Sets the month field (and optionally the day of the month) of a date, using local or universal time.

set[UTC]Seconds( )
Sets the seconds field (and optionally the milliseconds field) of a date, using local or universal time.

setTime( )
Sets the fields of a Date object using the millisecond format.

setYear( )
Sets the year field of a Date object. Deprecated in favor of setFullYear( ).

toDateString( )
Returns a string that represents the date portion of the date, expressed in the local time zone.

toGMTString( )
Converts a Date to a string, using the GMT time zone. Deprecated in favor of toUTCString( ).

toLocaleDateString( )
Returns a string that represents the date portion of the date, expressed in the local time zone, using the local date formatting conventions.

toLocaleString( )
Converts a Date to a string, using the local time zone and the local date formatting conventions.

toLocaleTimeString( )
Returns a string that represents the time portion of the date, expressed in the local time zone, using the local time formatting conventions.

toString( )
Converts a Date to a string using the local time zone.

toTimeString( )
Returns a string that represents the time portion of the date, expressed in the local time zone.

toUTCString( )
Converts a Date to a string, using universal time.

valueOf( )
Converts a Date to its internal millisecond format.

Static Methods

In addition to the many instance methods listed above, the Date object also defines two static methods. These methods are invoked through the Date( ) constructor itself, not through individual Date objects:

Date.parse( )
Parses a string representation of a date and time and returns the internal millisecond representation of that date.

Date.UTC( )
Returns the millisecond representation of the specified UTC date and time.

Description

The Date object is a data type built into the JavaScript language. Date objects are created with the new Date( ) syntax shown in the preceding Constructor section.

Once a Date object is created, there are a number of methods that allow you to operate on it. Most of the methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time. The toString( ) method and its variants convert dates to human-readable strings. getTime( ) and setTime( ) convert to and from the internal representation of the Date object -- the number of milliseconds since midnight (GMT) on January 1, 1970. In this standard millisecond format, a date and time are represented by a single integer, which makes date arithmetic particularly easy. The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so the JavaScript clock will not "roll over" until the year 275755.

Example

Once you create a Date object, there are a variety of methods you can use to operate on it:

d = new Date( );  // Get the current date and time
document.write('Today is: " + d.toLocaleDateString( ) + '. ');  // Display date
document.write('The time is: ' + d.toLocaleTimeString( ));      // Display time
var dayOfWeek = d.getDay( );                          // What weekday is it?
var weekend = (dayOfWeek == 0) || (dayOfWeek == 6);  // Is it a weekend?

Another common use of the Date object is to subtract the millisecond representations of the current time from some other time to determine the difference between the two times. The following client-side example shows two such uses:

<script language="JavaScript">
today = new Date( );      // Make a note of today's date
christmas = new Date( );  // Get a date with the current year
christmas.setMonth(11);    // Set the month to December...
christmas.setDate(25);     // and the day to the 25th

// If Christmas hasn't already passed, compute the number of
// milliseconds between now and Christmas, convert this
// to a number of days and print a message
if (today.getTime( ) < christmas.getTime( )) {
    difference = christmas.getTime( ) - today.getTime( );
    difference = Math.floor(difference / (1000 * 60 * 60 * 24));
    document.write('Only ' + difference + ' days until Christmas!<p>');
}
</script>

// ... rest of HTML document here ...

<script language="JavaScript">
// Here we use Date objects for timing
// We divide by 1000 to convert milliseconds to seconds
now = new Date( );
document.write('<p>It took ' +
    (now.getTime( )-today.getTime( ))/1000 +
    'seconds to load this page.');
</script>

See Also

Date.parse( ), Date.UTC( )

Date.UTC( )convert a Date specification to milliseconds

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Date.UTC(year, month, day, hours, minutes, seconds, ms)

Arguments

year
The year in four-digit format. If this argument is between 0 and 99, inclusive, 1900 will be added to it and it will be treated as a year between 1900 and 1999.

month
The month, specified as an integer from 0 ( January) to 11 (December).

day
The day of the month, specified as an integer from 1 to 31. Note that this argument uses 1 as its lowest value, while other arguments use 0 as their lowest value. This argument is optional.

hours
The hour, specified as an integer from 0 (midnight) to 23 (11 p.m.). This argument is optional.

minutes
The minutes in the hour, specified as an integer from 0 to 59. This argument is optional.

seconds
The seconds in the minute, specified as an integer from 0 to 59. This argument is optional.

ms
The number of milliseconds. This argument is optional and is ignored prior to ECMAScript standardization.

Returns

The millisecond representation of the specified universal time. That is, this method returns the number of milliseconds between midnight GMT on January 1, 1970 and the specified time.

Description

Date.UTC( ) is a static method; it is invoked through the Date( ) constructor, not through an individual Date object.

The arguments to Date.UTC( ) specify a date and time and are understood to be in UTC (Universal Coordinated Time) -- they are in the GMT time zone. The specified UTC time is converted to the millisecond format, which can be used by the Date( ) constructor method and by the Date.setTime( ) method.

The Date( ) constructor method can accept date and time arguments identical to those that Date.UTC( ) accepts. The difference is that the Date( ) constructor assumes local time, while Date.UTC( ) assumes universal time (GMT). To create a Date object using a UTC time specification, you can use code like this:

d = new Date(Date.UTC(1996, 4, 8, 16, 30));

See Also

Date, Date.parse( ), Date.setTime( )

encodeURI( )escape characters in a URI

Availability

JavaScript 1.5; JScript 5.5; ECMAScript v3

Synopsis

encodeURI(uri)

Arguments

uri
A string that contains the URI or other text to be encoded.

Returns

A copy of uri, with certain characters replaced by hexadecimal escape sequences.

Throws

URIError
Indicates that uri contains malformed Unicode surrogate pairs and cannot be encoded.

Description

encodeURI( ) is a global function that returns an encoded copy of its uri argument. ASCII letters and digits are not encoded, nor are the following ASCII punctuation characters:

- _ . ! ~ * ' ( ) 

Because encodeURI( ) is intended to encode complete URIs, the following ASCII punctuation characters, which have special meaning in URIs, are not escaped either:

; / ? : @ & = + $ , # 

Any other characters in uri are replaced by converting the character to its UTF-8 encoding and then encoding each of the resulting one, two, or three bytes with a hexadecimal escape sequence of the form %xx. In this encoding scheme, ASCII characters are replaced with a single %xx escape, characters with encodings between \u0080 and \u07ff are replaced with two escape sequences, and all other 16-bit Unicode characters are replaced with three escape sequences.

If you use this method to encode a URI, you should be certain that none of the components of the URI (such as the query string) contain URI separator characters such as ? and #. If the components may contain these characters, you should encode each component separately with encodeURIComponent( ).

Use decodeURI( ) to reverse the encoding applied by this method. Prior to ECMAScript v3, you can use escape( ) and unescape( ) methods (which are now deprecated) to perform a similar kind of encoding and decoding.

Example

// Returns http://www.isp.com/app.cgi?arg1=1&arg2=hello%20world
encodeURI("http://www.isp.com/app.cgi?arg1=1&arg2=hello world");
encodeURI("\u00a9");  // The copyright character encodes to %C2%A9

See Also

decodeURI( ), decodeURIComponent( ), encodeURIComponent( ), escape( ), unescape( )

Errora generic exception

Availability

JavaScript 1.5; JScript 5.5; ECMAScript v3

Inherits from/Overrides

Inherits from Object

Constructor

new Error( )
new Error(message)

Arguments

message
An optional error message that provides details about the exception.

Returns

A newly constructed Error object. If the message argument is specified, the Error object will use it as the value of its message property; otherwise, it will use an implementation-defined default string as the value of that property. When the Error( ) constructor is called as a function, without the new operator, it behaves just as it does when called with the new operator.

Properties

message
An error message that provides details about the exception. This property holds the string passed to the constructor or an implementation-defined default string.

name
A string that specifies the type of the exception. For instances of the Error class and all of its subclasses, this property specifies the name of the constructor used to create the instance.

Methods

toString( )
Returns an implementation-defined string that represents this Error object.

Description

Instances of the Error class represent errors or exceptions and are typically used with the throw and try/catch statements. The name property specifies the type of the exception, and the message property can be used to provide human-readable details about the exception.

The JavaScript interpreter never throws Error object directly; instead, it throws instances of one of the Error subclasses such as SyntaxError or RangeError. In your own code you may find it convenient to throw Error objects to signal exceptions, or you may prefer to simply throw an error message or error code as a primitive string or number value.

Note that the ECMAScript specification defines a toString( ) method for the Error class (it is inherited by each of the subclasses of Error) but that it does not require this toString( ) method to return a string that contains the contents of the message property. Therefore, you should not expect the toString( ) method to convert an Error object to convert to a meaningful human-readable string. To display an error message to a user, you should explicitly use the name and message properties of the Error object.

Example

You might signal an exception with code like the following:

function factorial(x) {
    if (x < 0) throw new Error("factorial: x must be >= 0");
    if (x <= 1) return 1; else return x * factorial(x-1);
}

And if you catch an exception, you might display its to the user with code like the following (which uses the client-side Window.alert( ) method):

try { &*(&/* an error is thrown here */ }
catch(e) {
    if (e instanceof Error) {  // Is it an instance of Error or a subclass?
        alert(e.name + ": " + e.message);
    }
} 

See Also

EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError

escape( )encode a string

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1; deprecated in ECMAScript v3

Synopsis

escape(s) 

Arguments

s
The string that is to be "escaped" or encoded.

Returns

An encoded copy of s in which certain characters have been replaced by hexadecimal escape sequences.

Description

escape( ) is a global function. It returns a new string that contains an encoded version of s. The string s itself is not modified.

escape( ) returns a string in which all characters of s other than ASCII letters, digits, and the punctuation characters @, *, _, +, -, ., and / have been replaced by escape sequences of the form %xx or %uxxxx (where x represents a hexadecimal digit). Unicode characters \u0000 to \u00ff are replaced with the %xx escape sequence, and all other Unicode characters are replaced with the %uxxxx sequence.

Use the unescape( ) function to decode a string encoded with escape( ).

In client-side JavaScript, a common use of escape( ) is to encode cookie values, which have restrictions on the punctuation characters they may contain. See the Document.cookie reference page in the client-side reference section.

Although the escape( ) function was standardized in the first version of ECMAScript, it has been deprecated and removed from the standard by ECMAScript v3. Implementations of ECMAScript are likely to implement this function, but they are not required to. In JavaScript 1.5 and JScript 5.5 and later, you should use encodeURI( ) and encodeURIComponent( ) instead of escape( ).

Example

escape("Hello World!");  // Returns "Hello%20World%21"

See Also

encodeURI( ), encodeURIComponent( ), String, escape( ); Document.cookie in the client-side reference section

eval( )execute JavaScript code from a string

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

eval(code) 

Arguments

code
A string that contains the JavaScript expression to be evaluated or the statements to be executed.

Returns

The value of the evaluated code, if any.

Throws

SyntaxError
Indicates that code does not contain legal JavaScript.

EvalError
Indicates that eval( ) was called illegally, through an identifier other than "eval", for example. See the restrictions on this function described below.

Other exception
If the JavaScript code passed to eval( ) generates an exception, eval( ) will pass that exception on to the caller.

Description

eval( ) is a global method that evaluates a string containing JavaScript code. If code contains an expression, eval evaluates the expression and returns its value. If code contains a JavaScript statement or statements, eval( ) executes those statements and returns the value, if any, returned by the last statement. If code does not return any value, eval( ) returns undefined. Finally, if code throws an exception, eval( ) passes that exception on to the caller.

eval( ) provides a very powerful capability to the JavaScript language, but its use is infrequent in real-world programs. Obvious uses are to write programs that act as recursive JavaScript interpreters and to write programs that dynamically generate and evaluate JavaScript code.

Most JavaScript functions and methods that expect string arguments accept arguments of other types as well and simply convert those argument values to strings before proceeding. eval( ) does not behave like this. If the code argument is not a primitive string, it is simply returned unchanged. Be careful, therefore, that you do not inadvertently pass a String object to eval( ) when you intended to pass a primitive string value.

For purposes of implementation efficiency, the ECMAScript v3 standard places an unusual restriction on the use of eval( ). An ECMAScript implementation is allowed to throw an EvalError exception if you attempt to overwrite the eval property or if you assign the eval( ) method to another property and attempt to invoke it through that property.

Example

eval("1+2");  // Returns 3

// This code uses client-side JavaScript methods to prompt the user to
// enter an expression and to display the results of evaluating it.
// See the client-side methods Window.alert( ) and Window.prompt( ) for details.
try {
    alert("Result: " +  eval(prompt("Enter an expression:","")));
}
catch(exception) {
    alert(exception);
}

var myeval = eval;  // May throw an EvalError
myeval("1+2");      // May throw an EvalError
Functiona JavaScript function

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Inherits from/Overrides

Inherits from Object

Synopsis

function functionname(argument_name_list) // Function definition statement 
{
    body 
} 
function (argument_name_list) { body } // Unnamed function literal; JavaScript 1.2 
functionname(argument_value_list)      // Function invocation

Constructor

new Function(argument_names..., body) // JavaScript 1.1 and later

Arguments

argument_names...
Any number of string arguments, each naming one or more arguments of the Function object being created.

body
A string that specifies the body of the function. It may contain any number of JavaScript statements, separated with semicolons, and may refer to any of the argument names specified by previous arguments to the constructor.

Returns

A newly created Function object. Invoking the function executes the JavaScript code specified by body.

Throws

SyntaxError
Indicates that there was a JavaScript syntax error in the body argument or in one of the argument_names arguments.

Properties

arguments[]
An array of arguments that were passed to the function. Deprecated.

caller
A reference to the Function object that invoked this one, or null if the function was invoked from top-level code. Deprecated.

length
The number of named arguments specified when the function was declared.

prototype
An object which, for a constructor function, defines properties and methods shared by all objects created with that constructor function.

Methods

apply( )
Invokes a function as a method of a specified object, passing a specified array of arguments.

call( )
Invokes a function as a method of a specified object, passing the specified arguments.

toString( )
Returns a string representation of the function.

Description

A function is a fundamental data type in JavaScript. Chapter 7 explains how to define and use functions, and Chapter 8 covers the related topics of methods, constructors, and the prototype property of functions. See those chapters for complete details. Note that although function objects may be created with the Function( ) constructor described here, this is not efficient, and the preferred way to define functions, in most cases, is with a function definition statement or a function literal.

In JavaScript 1.1 and later, the body of a function is automatically given a local variable, named arguments, that refers to an Arguments object. This object is an array of the values passed as arguments to the function. Don't confuse this with the deprecated arguments[] property listed above. See the Arguments reference page for details.

See Also

Arguments; Chapter 7; Chapter 8

Globalthe global object

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

this 

Global Properties

The global object is not a class, so the following global properties have individual reference entries under their own name. That is, you can find details on the undefined property listed under the name "undefined," not under "Global.undefined." Note that all top-level variables are also properties of the global object.

Infinity
A numeric value that represents positive infinity.

NaN
The not-a-number value.

undefined
The undefined value.

Global Functions

The global object is an object, not a class. The global functions listed below are not methods of any object, and their reference entries appear under the function name. For example, you'll find details on the parseInt( ) function under "parseInt( )," not "Global.parseInt( )."

decodeURI( )
Decodes a string escaped with encodeURI( ).

decodeURIComponent( )
Decodes a string escaped with encodeURIComponent( ).

encodeURI
Encodes a URI by escaping certain characters.

encodeURIComponent
Encodes a URI component by escaping certain characters.

escape( )
Encodes a string by replacing certain characters with escape sequences.

eval( )
Evaluates a string of JavaScript code and return the result.

isFinite( )
Tests whether a value is a finite number.

isNaN
Tests whether a value is the not-a-number value.

parseFloat( )
Parses a number from a string.

parseInt( )
Parses an integer from a string.

unescape( )
Decodes a string encoded with escape( ).

Global Objects

In addition to the global properties and functions listed above, the global object also defines properties that refer to all the other predefined JavaScript objects. All of these properties are constructor functions that define classes except for Math, which is a reference to an object that is not a constructor.

Array
The Array( ) constructor.

Boolean
The Boolean( ) constructor.

Date
The Date( ) constructor.

Error
The Error( ) constructor.

EvalError
The EvalError( ) constructor.

Function
The Function( ) constructor.

Math
A reference to an object that defines mathematical functions.

Number
The Number( ) constructor.

Object
The Object( ) constructor.

RangeError
The RangeError( ) constructor.

ReferenceError
The ReferenceError( ) constructor.

RegExp
The RegExp( ) constructor.

String
The String( ) constructor.

SyntaxError
The SyntaxError( ) constructor.

TypeError
The TypeError( ) constructor.

URIError
The URIError( ) constructor.

Description

The global object is a predefined object that serves as a placeholder for the global properties and functions of JavaScript. All other predefined objects, functions, and properties are accessible through the global object. The global object is not a property of any other object, so it does not have a name. (The title of this reference page was chosen simply for organizational convenience and does not indicate that the global object is named "Global"). In top-level JavaScript code, you can refer to the global object with the keyword this. It is rarely necessary to refer to the global object in this way, however, because the global object serves as the top of the scope chain, which means that unqualified variable and function names are looked up as properties of the object. When JavaScript code refers to the parseInt( ) function, for example, it is referring to the parseInt property of the global object. The fact that the global object is the top of the scope chain also means that all variables declared in top-level JavaScript code become properties of the global object.

The global object is simply an object, not a class. There is no Global( ) constructor, and there is no way to instantiate a new global object.

When JavaScript is embedded in a particular environment, the global object is usually given additional properties that are specific to that environment. In fact, the type of the global object is not specified by the ECMAScript standard, and an implementation or embedding of JavaScript may use an object of any type as the global object, as long as the object defines the basic properties and functions listed here. In client-side JavaScript, for example, the global object is a Window object and represents the web browser window within which the JavaScript code is running.

Example

In core JavaScript, none of the predefined properties of the global object are enumerable, so you can list all implicitly and explicitly declared global variables with a for/in loop like this:

var variables = ""
for(var name in this)
    variables += name + "\n";

See Also

Window in the client-side reference section; Chapter 4

Mathmathematical functions and constants

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Math.constant 
Math.function( )

Constants

Math.E
The constant e the base of the natural logarithms.

Math.LN10
The natural logarithm of 10.

Math.LN2
The natural logarithm of 2.

Math.LOG10E
The base-10 logarithm of e

Math.LOG2E
The base-2 logarithm of e

Math.PI
The constant Figure .

Math.SQRT1_2
1 divided by the square root of 2.

Math.SQRT2
The square root of 2.

Static Functions

Math.abs( )
Computes an absolute value.

Math.acos( )
Computes an arc cosine.

Math.asin( )
Computes an arc sine.

Math.atan( )
Computes an arc tangent.

Math.atan2( )
Computes the angle from the X-axis to a point.

Math.ceil( )
Rounds a number up.

Math.cos( )
Computes a cosine.

Math.exp( )
Computes an exponent of e

Math.floor( )
Rounds a number down.

Math.log( )
Computes a natural logarithm.

Math.max( )
Returns the larger of two numbers.

Math.min( )
Returns the smaller of two numbers.

Math.pow( )
Computes xy

Math.random( )
Computes a random number.

Math.round( )
Rounds to the nearest integer.

Math.sin( )
Computes a sine.

Math.sqrt( )
Computes a square root.

Math.tan( )
Computes a tangent.

Description

Math is an object that defines properties that refer to useful mathematical functions and constants. These functions and constants are conveniently grouped by this Math object and are invoked with syntax like this:

y = Math.sin(x);
area = radius * radius * Math.PI; 

Math is not a class of objects like Date and String are. There is no Math( ) constructor, and functions like Math.sin( ) are simply functions, not methods that operate on an object.

See Also

Number

Numbersupport for numbersNumber object

Availability

JavaScript 1.1; JScript 2.0; ECMAScript v1

Inherits from/Overrides

Inherits from Object

Constructor

new Number(value)
Number(value)

Arguments

value
The numeric value of the Number object being created, or a value to be converted to a number.

Returns

When Number( ) is used with the new operator as a constructor, it returns a newly constructed Number object. When Number( ) is invoked as a function without the new operator, it converts its argument to a primitive numeric value and returns that value (or NaN if the conversion failed).

Constants

Number.MAX_VALUE
The largest representable number.

Number.MIN_VALUE
The smallest representable number.

Number.NaN
Not-a-number value.

Number.NEGATIVE_INFINITY
Negative infinite value; returned on overflow.

Number.POSITIVE_INFINITY
Infinite value; returned on overflow.

Methods

toString( )
Converts a number to a string, using a specified radix (base).

toLocaleString( )
Converts a number to a string, using local number formatting conventions.

toFixed( )
Converts a number to a string that contains a specified number of digits after the decimal place.

toExponential( )
Converts a number to a string using exponential notation with the specified number of digits after the decimal place.

toPrecision( )
Converts a number to a string using the specified number of significant digits. Uses exponential or fixed-point notation depending on the size of the number and the number of significant digits specified.

Description

Numbers are a basic, primitive data type in JavaScript. In JavaScript 1.1, however, JavaScript also supports the Number object, which is a wrapper object around a primitive numeric value. JavaScript automatically converts between the primitive and object forms as necessary. In JavaScript 1.1, you can explicitly create a Number object with the Number( ) constructor, although there is rarely any need to do so.

The Number( ) constructor can also be used without the new operator, as a conversion function. When invoked in this way, it attempts to convert its argument to a number and returns the primitive numeric value (or NaN) that results from the conversion.

The Number( ) constructor is also used as a placeholder for five useful numeric constants: the largest and smallest representable numbers; positive and negative infinity; and the special not-a-number value. Note that these values are properties of the Number( ) constructor function itself, not of individual number objects. For example, you can use the MAX_VALUE property as follows:

var biggest = Number.MAX_VALUE 

but not like this:

var n = new Number(2);
var biggest = n.MAX_VALUE 

By contrast, the toString( ) and other methods of the Number object are methods of each Number object, not of the Number( ) constructor function. As noted earlier, JavaScript automatically converts from primitive numeric values to Number objects whenever necessary. This means that we can use the Number methods with primitive numeric values as well as with Number objects.

var value = 1234;
var binary_value = n.toString(2); 

See Also

Infinity, Math, NaN

Objecta superclass that contains features of all

Availability

JavaScript objectsJavaScript 1.0; JScript 1.0; ECMAScript v1

Constructor

new Object( )new 
Object(value)

Arguments

value
This optional argument specifies a primitive JavaScript value -- a number, boolean, or string -- that is to be converted to a Number, Boolean, or String object. This object is not supported prior to JavaScript 1.1 and ECMAScript v1.

Returns

If no value argument is passed, this constructor returns a newly created Object instance. If a primitive value argument is specified, the constructor creates and returns a Number, Boolean, or String object wrapper for the primitive value. When the Object( ) constructor is called as a function, without the new operator, it behaves just as it does when used with the new operator.

Properties

constructor
A reference to the JavaScript function that was the constructor for the object.

Methods

hasOwnProperty( )
Checks whether an object has a locally defined (noninherited) property with a specified name.

isPrototypeOf( )
Checks whether this object is the prototype object of a specified object.

propertyIsEnumerable( )
Checks whether a named property exists and would be enumerated by a for/in loop.

toLocaleString( )
Returns a localized string representation of the object. The default implementation of this method simply calls toString( ), but subclasses may override it to provide localization.

toString( )
Returns a string representation of the object. The implementation of this method provided by the Object class is quite generic and does not provide much useful information. Subclasses of Object typically override this method by defining their own toString( ) method which produces more useful output.

valueOf( )
Returns the primitive value of the object, if any. For objects of type Object, this method simply returns the object itself. Subclasses of Object, such as Number and Boolean, override this method to return the primitive value associated with the object.

Description

The Object class is a built-in data type of the JavaScript language. It serves as the superclass for all other JavaScript objects; therefore, methods and behavior of the Object class are inherited by all other objects. The basic behavior of objects in JavaScript is explained in Chapter 8.

In addition to the Object( ) constructor shown above, objects can also be created and initialized using the Object literal syntax described in Chapter 8.

See Also

Array, Boolean, Function, Function.prototype, Number, String; Chapter 8

Object.hasOwnProperty( )check whether a property is inherited

Availability

JavaScript 1.5; JScript 5.5; ECMAScript v3

Synopsis

object.hasOwnProperty(propname)

Arguments

propname
A string that contains the name of a property of object.

Returns

true if object has a noninherited property with the name specified by propname. Returns false if object does not have a property with the specified name or if it inherits that property from its prototype object.

Description

As explained in Chapter 8, JavaScript objects may have properties of their own, and they may also inherit properties from their prototype object. The hasOwnProperty( ) method provides a way to distinguish between inherited properties and noninherited local properties.

Example

var o = new Object( );          // Create an object
o.x = 3.14;                      // Define a noninherited local property
o.hasOwnProperty("x");           // Returns true: x is a local property of o
o.hasOwnProperty("y");           // Returns false: o doesn't have a property y
o.hasOwnProperty("toString");    // Returns false: toString property is inherited

See Also

Function.prototype, Object.propertyIsEnumerable( ); Chapter 8

Object.isPrototypeOf( )is one object the prototype of another?

Availability

JavaScript 1.5; JScript 5.5; ECMAScript v3

Synopsis

object.isPrototypeOf(o)

Arguments

o
Any object.

Returns

true if object is the prototype of o. Returns false if o is not an object or if object is not the prototype of o.

Description

As explained in Chapter 8, JavaScript objects inherit properties from their prototype object. The prototype of an object is referred to by the prototype property of the constructor function used to create and initialize the object. The isPrototypeOf( ) method provides a way to determine if one object is the prototype of another. This technique can be used to determine the class of an object.

Example

var o = new Object( );                          // Create an object
Object.prototype.isPrototypeOf(o)                // true: o is an object
Function.prototype.isPrototypeOf(o.toString);    // true: toString is a function
Array.prototype.isPrototypeOf([1,2,3]);          // true: [1,2,3] is an array

// Here is a way to perform a similar test
(o.constructor == Object);  // true: o was created with Object( ) constructor
(o.toString.constructor == Function);  // true: o.toString is a function

// Prototype objects themselves have prototypes. The following call
// returns true, showing that function objects inherit properties
// from Function.prototype and also from Object.prototype.
Object.prototype.isPrototypeOf(Function.prototype);

See Also

Function.prototype, Object.constructor; Chapter 8

Object.propertyIsEnumerable( )will property be seen by a for/in loop?

Availability

JavaScript 1.5; JScript 5.5; ECMAScript v3

Synopsis

object.propertyIsEnumerable(propname)

Arguments

propname
A string that contains the name of a property of object.

Returns

true if object has a noninherited property with the name specified by propname and if that property is "enumerable," which means that it would be enumerated by a for/in loop on object.

Description

The for/in statement loops through the "enumerable" properties of an object. Not all properties of an object are enumerable, however: properties added to an object by JavaScript code are enumerable, but the predefined properties (such as methods) of built-in objects are not usually enumerable. The propertyIsEnumerable( ) method provides a way to distinguish between enumerable and nonenumerable properties. Note, however, that the ECMAScript specification states that propertyIsEnumerable( ) does not examine the prototype chain, which means that it only works for local properties of an object and does not provide any way to test the enumerability of inherited properties.

Example

var o = new Object( );                // Create an object
o.x = 3.14;                            // Define a property
o.propertyIsEnumerable("x");           // true: property x is local and enumerable
o.propertyIsEnumerable("y");           // false: o doesn't have a property y
o.propertyIsEnumerable("toString");    // false: toString property is inherited
Object.prototype.propertyIsEnumerable("toString");  // false: nonenumerable

Bugs

The specification is apparently in error when it restricts propertyIsEnumerable( ) to check only noninherited properties. Internet Explorer 5.5 implements this method as specified. Netscape 6.0 implements it so that it does consider the prototype chain. Although this is the way the method was probably intended to work, it violates the specification, and Netscape 6.1 has been modified to match the IE 5.5. Because of the error in the specification, this method is less useful than it should be.

See Also

Function.prototype, Object.hasOwnProperty( ); Chapter 8

Object.toString( )define an object's string representation

Availability

JavaScript 1.0; JScript 2.0; ECMAScript v1

Synopsis

object.toString( )

Returns

A string representing the object.

Description

The toString( ) method is not one you often call explicitly in your JavaScript programs. Instead, you define this method in your objects, and the system calls it whenever it needs to convert your object to a string.

The JavaScript system invokes the toString( ) method to convert an object to a string whenever the object is used in a string context. For example, if an object is converted to a string when it is passed to a function that expects a string argument:

alert(my_object); 

Similarly, objects are converted to strings when they are concatenated to strings with the + operator:

var msg = 'My object is: ' + my_object; 

The toString( ) method is invoked without arguments and should return a string. To be useful, the string you return should be based, in some way, on the value of the object for which the method was invoked.

When you define a custom class in JavaScript, it is good practice to define a toString( ) method for the class. If you do not, the object inherits the default toString( ) method from the Object class. This default method returns a string of the form:

[object class] 

where class is the class of the object: a value such as "Object", "String", "Number", "Function", "Window", "Document", and so on. This behavior of the default toString( ) method is occasionally useful to determine the type or class of an unknown object. Because most objects have a custom version of toString( ), however, you must explicitly invoke the Object.toString( ) method on an object o with code like this:

Object.prototype.toString.apply(o); 

Note that this technique for identifying unknown objects works only for built-in objects. If you define your own object class, it will have a class of "Object". In this case, you can use the Object.constructor property to obtain more information about the object.

The toString( ) method can be quite useful when you are debugging JavaScript programs -- it allows you to print objects and see their value. For this reason alone, it is a good idea to define a toString( ) method for every object class you create.

Although the toString( ) method is usually invoked automatically by the system, there are times when you may invoke it yourself. For example, you might want to do an explicit conversion of an object to a string in a situation where JavaScript does not do it automatically for you:

y = Math.sqrt(x);       // Compute a number
ystr = y.toString( );  // Convert it to a string 

Note in this example that numbers have a built-in toString( ) method that you can use to force a conversion.

In other circumstances, you might choose to use a toString( ) call even in a context where JavaScript would do the conversion automatically. Using toString( ) explicitly can help to make your code clearer:

alert(my_obj.toString( )); 

See Also

Object.constructor, Object.toLocaleString( ), Object.valueOf( )

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

Availability

JavaScript 1.1; JScript 2.0; ECMAScript v1

Synopsis

object.valueOf( )

Returns

The primitive value associated with the object, if any. If there is no value associated with object, returns the object itself.

Description

The valueOf( ) method of an object returns the primitive value associated with that object, if there is one. For objects of type Object there is no primitive value, and this method simply returns the object itself.

For objects of type Number, however, valueOf( ) returns the primitive numeric value represented by the object. Similarly, it returns the primitive boolean value associated with a Boolean object and the string associated with a String object.

It is rarely necessary to invoke the valueOf( ) method yourself. JavaScript does this automatically whenever an object is used where a primitive value is expected. In fact, because of this automatic invocation of the valueOf( ) method, it is difficult to even distinguish between primitive values and their corresponding objects. The typeof operator shows you the difference between strings and String objects for example, but in practical terms, you can use them equivalently in your JavaScript code.

The valueOf( ) methods of the Number, Boolean, and String objects convert these wrapper objects to the primitive values they represent. The Object( ) constructor performs the opposite operation when invoked with a number, boolean, or string argument: it wraps the primitive value in an appropriate object wrapper. JavaScript performs this primitive-to-object conversion for you in almost all circumstances, so it is rarely necessary to invoke the Object( ) constructor in this way.

In some circumstances, you may want to define a custom valueOf( ) method for your own objects. For example, you might define a JavaScript object type to represent complex numbers (a real number plus an imaginary number). As part of this object type, you would probably define methods for performing complex addition, multiplication, and so on. But you might also want the ability to treat your complex numbers like ordinary real numbers by discarding the imaginary part. To achieve this, you might do something like the following:

Complex.prototype.valueOf = new Function("return this.real"); 

With this valueOf( ) method defined for your Complex object type, you could then do things like pass one of your complex number objects to Math.sqrt( ), which would compute the square root of the real portion of the complex number.

See Also

Object.toString( )

parseInt( )convert a string to an integer

Availability

JavaScript 1.0; JScript 1.1; ECMAScript v1

Synopsis

parseInt(s)
parseInt(s, radix)

Arguments

s
The string to be parsed.

radix
An optional integer argument that represents the radix (i.e., base) of the number to be parsed. If this argument is omitted or is 0, the number is parsed in base 10, or in base 16 if it begins with "0x" or "0X". If this argument is less than 2 or greater than 36, parseInt( ) returns NaN.

Returns

The parsed number, or NaN if s does not begin with a valid integer. In JavaScript 1.0, parseInt( ) returns 0 instead of NaN when it cannot parse s.

Description

parseInt( ) parses and returns the first number (with an optional leading minus sign) that occurs in s. Parsing stops, and the value is returned, when parseInt( ) encounters a character in s that is not a valid digit for the specified radix. If s does not begin with a number that parseInt( ) can parse, the function returns the not-a-number value NaN. Use the isNaN( ) function to test for this return value.

The radix argument specifies the base of the number to be parsed. Specifying 10 makes the parseInt( ) parse a decimal number. The value 8 specifies that an octal number (using digits 0 through 7) is to be parsed. The value 16 specifies a hexadecimal value, using digits 0 through 9 and letters A through F. radix can be any value between 2 and 36.

If radix is 0 or is not specified, parseInt( ) tries to determine the radix of the number from s. If s begins (after an optional minus sign) with 0x, parseInt( ) parses the remainder of s as a hexadecimal number. If s begins with a 0, the ECMAScript v3 standard allows an implementation of parseInt( ) to interpret the following characters as an octal number or as a decimal number. Otherwise, if s begins with a digit from 1 through 9, parseInt( ) parses it as a decimal number.

Example

parseInt("19", 10);  // Returns 19  (10 + 9)
parseInt("11", 2);   // Returns 3   (2 + 1)
parseInt("17", 8);   // Returns 15  (8 + 7)
parseInt("1f", 16);  // Returns 31  (16 + 15)
parseInt("10");      // Returns 10
parseInt("0x10");    // Returns 16
parseInt("010");     // Ambiguous: returns 10 or 8

Bugs

When no radix is specified, ECMAScript v3 allows an implementation to parse a string that begins with "0" (but not "0x" or "0X") as an octal or as a decimal number. To avoid this ambiguity, you should explicitly specify a radix or leave the radix unspecified only when you are sure that all numbers to be parsed will be decimal or hexadecimal numbers with the "0x" or "0X" prefix.

In JavaScript 1.0, NaN is not supported, and parseInt( ) returns 0 instead of NaN when it cannot parse s. In this version of the language, parseInt( ) cannot distinguish between malformed input and a the legal input "0".

See Also

isNaN( ), parseFloat( )

RegExpregular expressions for pattern matching RegExp object pattern matching (and regular expressions)RegExp object

Availability

JavaScript 1.2; JScript 3.0; ECMAScript v3

Literal Syntax

/pattern/attributes

Constructor

new RegExp(pattern, attributes)

Arguments

pattern
A string that specifies the pattern of the regular expression, or another regular expression.

attributes
An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multiline matches. The "m" attribute is not available prior to ECMAScript standardization. If the pattern argument is a regular expression instead of a string, this argument must be omitted.

Returns

A new RegExp object, with the specified pattern and flags. If the pattern argument is a regular expression rather than a string, the RegExp( ) constructor creates a new RegExp object using the same pattern and flags as the specified RegExp. If RegExp( ) is called as a function without the new operator, it behaves just as it would with the new operator, except when pattern is a regular expression; in that case, it simply returns pattern instead of creating a new RegExp object.

Throws

SyntaxError
If pattern is not a legal regular expression or if attributes contains characters other than "g", "i", and "m".

TypeError
If pattern is a RegExp object and the attributes argument is not omitted.

Instance Properties

global
Whether the RegExp has the g attribute.

ignoreCase
Whether the RegExp has the i attribute.

lastIndex
The character position of the last match; used for finding multiple matches in a string.

multiline
Whether the RegExp has the m attribute.

source
The source text of the regular expression.

Methods

exec( )
Performs powerful, general-purpose pattern matching.

test( )
Tests whether a string contains a pattern.

Description

The RegExp object represents a regular expression, a powerful tool for performing pattern matching on strings. See Chapter 10 for complete details on regular expression syntax and use.

See Also

Chapter 10

RegExp.exec( )general-purpose pattern matching

Availability

JavaScript 1.2; JScript 3.0; ECMAScript v3

Synopsis

regexp.exec(string)

Arguments

string
The string to be searched.

Returns

An array containing the results of the match, or null if no match was found. The format of the returned array is described below.

Throws

TypeError
If this method is invoked on an object that is not a RegExp.

Description

exec( ) is the most powerful of all the RegExp and String pattern matching methods. It is a general-purpose method that is somewhat more complex to use than RegExp.test( ), String.search( ), String.replace( ), and String.match( ).

exec( ) searches string for text that matches regexp. If it finds a match, it returns an array of results; otherwise, it returns null. Element 0 of the returned array is the matched text. Element 1 is the text that matched the first parenthesized subexpression, if any, within regexp. Element 2 contains the text that matched the second subexpression, and so on. The array length property specifies the number of elements in the array, as usual. In addition to the array elements and the length property, the value returned by exec( ) also has two other properties. The index property specifies the character position of the first character of the matched text. The input property refers to string. This returned array is the same as the array that is returned by the String.match( ) method, when invoked on a nonglobal RegExp object.

When exec( ) is invoked on a nonglobal pattern, it performs the search and returns the result described above. When regexp is a global regular expression, however, exec( ) behaves in a slightly more complex way. It begins searching string at the character position specified by the lastIndex property of regexp. When it finds a match, it sets lastIndex to the position of the first character after the match. This means that you can invoke exec( ) repeatedly in order to loop through all matches in a string. When exec( ) cannot find any more matches, it returns null and resets lastIndex to zero. If you begin searching a new string immediately after successfully finding a match in another string, you must be careful to manually reset lastIndex to zero.

Note that exec( ) always includes full details of every match in the array it returns, whether or not regexp is a global pattern. This is where exec( ) differs from String.match( ), which returns much less information when used with global patterns. Calling the exec( ) method repeatedly in a loop is the only way to obtain complete pattern matching information for a global pattern.

Example

You can use exec( ) in a loop to find all matches within a string. For example:

var pattern = /\bJava\w*\b/g;
var text = "JavaScript is more fun than Java or JavaBeans!";
var result;
while((result = pattern.exec(text)) != null) {
    alert("Matched `" + result[0] +
          "' at position " + result.index +
          " next search begins at position " + pattern.lastIndex);
}

Bugs

In JScript 3.0, exec( ) does not properly set or use the lastIndex property, so it cannot be used with global patterns in the kind of loop shown in the example above.

See Also

RegExp.lastIndex, RegExp.test( ), String.match( ), String.replace( ), String.search( ); Chapter 10

RegExp.globalwhether a regular expression matches globally global property g attribute (global matching)

Availability

JavaScript 1.2; JScript 5.5; ECMAScript v3

Synopsis

regexp.global 

Description

global is a read-only boolean property of RegExp objects. It specifies whether a particular regular expression performs global matching; i.e., whether it was created with the g attribute.

RegExp.ignoreCasewhether a regular expression is case-insensitive ignoreCase property caseinsensitivity toin pattern matching i attribute (case-insensitive matching)

Availability

JavaScript 1.2; JScript 5.5; ECMAScript v3

Synopsis

regexp.ignoreCase 

Description

ignoreCase is a read-only boolean property of RegExp objects. It specifies whether a particular regular expression performs case-insensitive matching; i.e.,whether it was created with the i attribute.

Stringsupport for stringsString object

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Inherits from/Overrides

Inherits from Object

Constructor

new String(s) // Constructor function
String(s) // Conversion function

Arguments

s
The value to be stored in a String object or converted to a primitive string.

Returns

When String( ) is used as a constructor with the new operator, it returns a String object, which holds the string s or the string representation of s. When the String( ) constructor is used without the new operator, it simply converts s to a primitive string and returns the converted value.

Properties

length
The number of characters in the string.

Methods

charAt( )
Extracts the character at a given position from a string.

charCodeAt( )
Returns the encoding of the character at a given position in a string.

concat( )
Concatenates one or more values to a string.

indexOf( )
Searches the string for a character or substring.

lastIndexOf( )
Searches the string backward for a character or substring.

match( )
Performs pattern matching with a regular expression.

replace( )
Performs a search-and-replace operation with a regular expression.

search( )
Searches a string for a substring that matches a regular expression.

slice( )
Returns a slice or substring of a string.

split( )
Splits a string into an array of strings, breaking at a specified delimiter string or regular expression.

substring( )
Extracts a substring of a string.

substr( )
Extracts a substring of a string. A variant of substring( ).

toLowerCase( )
Returns a copy of the string, with all characters converted to lowercase.

toString( )
Returns the primitive string value.

toUpperCase( )
Returns a copy of the string, with all characters converted to uppercase.

valueOf( )
Returns the primitive string value.

Static Methods

String.fromCharCode( )
Creates a new string using the character codes passed as arguments.

HTML Methods

Since JavaScript 1.0 and JScript 1.0, the String class has defined a number of methods that return a string modified by placing it within HTML tags. These methods have never been standardized by ECMAScript but can be useful in both client-side and server-side JavaScript code that dynamically generates HTML. If you are willing to use nonstandard methods, you might create the HTML source for a bold, red hyperlink, with code like this:

var s = "click here!";
var html = s.bold( ).link("javascript:alert('hello')").fontcolor("red"); 

Because these methods are not standardized, they do not have individual reference entries in the pages that follow:

anchor(name)
Returns a copy of the string, in an <a name=> environment.

big( )
Returns a copy of the string, in a <big> environment.

blink( )
Returns a copy of the string, in a <blink> environment.

bold( )
Returns a copy of the string, in a <b> environment.

fixed( )
Returns a copy of the string, in a <tt> environment.

fontcolor(color)
Returns a copy of the string, in a <font color=> environment.

fontsize(size)
Returns a copy of the string, in a <font size=> environment.

italics( )
Returns a copy of the string, in a <i> environment.

link(url)
Returns a copy of the string, in a <a href=> environment.

small( )
Returns a copy of the string, in a <small> environment.

strike( )
Returns a copy of the string, in a <strike> environment.

sub( )
Returns a copy of the string, in a <sub> environment.

sup( )
Returns a copy of the string, in a <sup> environment.

Description

Strings are a primitive data type in JavaScript. The String class type exists to provide methods for operating on primitive string values. The length property of a String object specifies the number of characters in the string. The String class defines a number of methods for operating on strings: there are methods for extracting a character or a substring from the string or searching for a character or a substring, for example. Note that JavaScript strings are immutable: none of the methods defined by the String class allows you to change the contents of a string. Instead, methods like String.toUpperCase( ) return an entirely new string, without modifying the original.

In Netscape implementations of JavaScript 1.2 and later, strings behave like read-only arrays of characters. For example, to extract the 3rd character from a string s, you could write s[2] instead of the more standard s.charAt(2). In addition, when the for/in statement is applied to a string, it enumerates these array indexes for each character in the string. (Note, however, that the length property is not enumerated, as per the ECMAScript specification.) Because this string-as-array behavior of Netscape's implementations is not standard, you should usually avoid using it.

See Also

Chapter 3

String.lastIndexOf( )search a string backwardlastIndexOf() method

Availability

JavaScript 1.0; JScript 1.0, ECMAScript v1

Synopsis

string.lastIndexOf(substring) 
string.lastIndexOf(substring, start)

Arguments

substring
The substring that is to be searched for within string.

start
An optional integer argument that specifies the position within string where the search is to start. Legal values are from 0 (the position of the first character in the string) to string.length-1 (the position of the last character in the string). If this argument is omitted, the search begins with the last character of the string.

Returns

The position of the last occurrence of substring within string that appears before the start position, if any, or -1 if no such occurrence is found within string.

Description

String.lastIndexOf( ) searches the string from end to beginning to see if it contains an occurrence of substring. The search begins at position start within string, or at the end of string if start is not specified. If an occurrence of substring is found, String.lastIndexOf( ) returns the position of the first character of that occurrence. Since this method searches from end to beginning of the string, the first occurrence found is the last one in the string that occurs before the start position.

If no occurrence of substring is found, String.lastIndexOf( ) returns -1.

Note that although String.lastIndexOf( ) searches string from end to beginning, it still numbers character positions within string from the beginning. The first character of the string has position 0 and the last has position string.length-1.

See Also

String.charAt( ), String.indexOf( ), String.substring( )

String.localeCompare( )compare one string to another, using locale-specific ordering

Availability

JavaScript 1.5; JScript 5.5; ECMAScript v3

Synopsis

string.localeCompare(target)

Arguments

target
A string to be compared, in a locale-sensitive fashion, with string.

Returns

A number that indicates the result of the comparison. If string is "less than" target, localeCompare( ) returns a number less than zero. If string is "greater than" target, the method returns a number greater than zero. And if the strings are identical or indistinguishable according to the locale ordering conventions, the method returns 0.

Description

When the < and > operators are applied to strings, they compare those strings using only the Unicode encodings of those characters and do not consider the collation order of the current locale. The ordering produced in this way is not always correct. Consider Spanish, for example, in which the letters "ch" are traditionally sorted as if they were a single letter that appeared between the letters "c" and "d".

localeCompare( ) provides a way to compare strings that does take the collation order of the default locale into account. The ECMAScript standard does not specify how the locale-specific comparison is done; it merely specifies that this function utilizes the collation order provided by the underlying operating system.

Example

You can use code like the following to sort an array of strings into a locale-specific ordering:

var strings;  // The array of strings to sort; initialized elsewhere
strings.sort(function(a,b) { return a.localeCompare(b) });
String.match( )find one or more regular expression matches

Availability

JavaScript 1.2; JScript 3.0; ECMAScript v3

Synopsis

string.match(regexp)

Arguments

regexp
A RegExp object that specifies the pattern to be matched. If this argument is not a RegExp, it is first converted to one by passing it to the RegExp( ) constructor.

Returns

An array containing the results of the match. The contents of the array depend on whether regexp has the global g attribute set. Details on this return value are given below.

Description

match( ) searches string for one or more matches of regexp. The behavior of this method depends significantly on whether regexp has the g attribute or not. See Chapter 10 for full details on regular expressions.

If regexp does not have the g attribute, match( ) searches string for a single match. If no match is found, match( ) returns null. Otherwise, it returns an array containing information about the match that it found. Element 0 of the array contains the matched text. The remaining elements contain the text that matched any parenthesized subexpressions within the regular expression. In addition to these normal array elements, the returned array also has two object properties. The index property of the array specifies the character position within string of the start of the matched text. Also, the input property of the returned array is a reference to string itself.

If regexp has the g flag, match( ) does a global search, searching string for all matching substrings. It returns null if no match is found, and it returns an array if one or more matches are found. The contents of this returned array are quite different for global matches, however. In this case, the array elements contain each of the matched substrings within string. The returned array does not have index or input properties in this case. Note that for global matches, match( ) does not provide information about parenthesized subexpressions, nor does it specify where within string each match occurred. If you need to obtain this information for a global search, you can use RegExp.exec( ).

Example

The following global match finds all numbers within a string:

"1 plus 2 equals 3".match(/\d+/g)  // Returns ["1", "2", "3"] 

The following nonglobal match uses a more complex regular expression with several parenthesized subexpressions. It matches a URL, and its subexpressions match the protocol, host, and path portions of the URL:

var url = /(\w+):\/\/([\w.]+)\/(\S*)/;
var text = "Visit my home page at http://www.isp.com/~david";
var result = text.match(url);
if (result != null) {
    var fullurl = result[0];   // Contains "http://www.isp.com/~david"
    var protocol = result[1];  // Contains "http"
    var host = result[2];      // Contains "www.isp.com"
    var path = result[3];      // Contains "~david"
} 

See Also

RegExp, RegExp.exec( ), RegExp.test( ), String.replace( ), String.search( ); Chapter 10

String.replace( )replace substring(s) matching a regular expressionreplace() methodString object regular expressionsreplacing substrings that match pattern matching (and regular expressions)substring matches, replacing

Availability

JavaScript 1.2; JScript 3.0; ECMAScript v3

Synopsis

string.replace(regexp, replacement)

Arguments

regexp
The RegExp object that specifies the pattern to be replaced. If this argument is a string, it is used as a literal text pattern to be searched for; it is not first converted to a RegExp object.

replacement
A string that specifies the replacement text, or a function that is invoked to generate the replacement text. See the Section section for details.

Returns

A new string, with the first match, or all matches, of regexp replaced with replacement.

Description

replace( ) performs a search-and-replace operation on string. It searches string for one or more substrings that match regexp and replaces them with replacement. If regexp has the global g attribute specified, replace( ) replaces all matching substrings. Otherwise, it replaces only the first matching substring.

replacement may be a string or a function. If it is a string, each match is replaced by the string. Except, however, that the $ character has special meaning within the replacement string. As shown in the following table, it indicates that a string derived from the pattern match is to be used in the replacement.

Characters

Replacement

$1, $2, ... $99

The text that matched the 1st through 99th parenthesized subexpression within regexp

$&

The substring that matched regexp

$`

The text to the left of the matched substring

$'

The text to the right of the matched substring

$$

A literal dollar sign

ECMAScript v3 specifies that the replacement argument to replace( ) may be a function instead of a string, and this feature is implemented in JavaScript 1.2 and JScript 5.5. In this case, the function is invoked for each match and the string it returns is used as the replacement text. The first argument to the function is the string that matched the pattern. The next arguments are the strings that matched any parenthesized subexpressions within the pattern. There may be zero or more of these arguments. The next argument is an integer that specifies the position within string at which the match occurred, and the final argument to the replacement function is string itself.

Example

To ensure that the capitalization of the word "JavaScript" is correct:

text.replace(/javascript/i, "JavaScript"); 

To convert a single name from "Doe, John" format to "John Doe" format:

name.replace(/(\w+)\s*,\s*(\w+)/, "$2 $1"); 

To replace all double quotes with double back and forward single quotes:

text.replace(/"([^"]*)"/g, "``$1''"); 

To capitalize the first letter of all words in a string:

text.replace(/\b\w+\b/g, function(word) {
                           return word.substring(0,1).toUpperCase( ) +
                                  word.substring(1);
                         }); 

See Also

RegExp, RegExp.exec( ), RegExp.test( ), String.match( ), String.search( ); Chapter 10

String.slice( )extract a substring slice() methodString object

Availability

JavaScript 1.2; JScript 3.0; ECMAScript v3

Synopsis

string.slice(start, end)

Arguments

start
The string index where the slice is to begin. If negative, this argument specifies a position measured from the end of the string. That is, -1 indicates the last character, -2 indicates the second from last character, and so on.

end
The string index immediately after the end of the slice. If not specified, the slice includes all characters from start to the end of the string. If this argument is negative, it specifies a position measured from the end of the string.

Returns

A new string that contains all the characters of string from and including start and up to but not including end.

Description

slice( ) returns a string containing a slice, or substring, of string. It does not modify string.

The String methods slice( ), substring( ), and the deprecated substr( ) all return specified portions of a string. slice( ) is more flexible than substring( ) because it allows negative argument values. slice( ) differs from substr( ) in that it specifies a substring with two character positions, while substr( ) uses one position and a length. Note also that String.slice( ) is an analog of Array.slice( ).

Example

var s = "abcdefg";
s.slice(0,4)    // Returns "abcd"
s.slice(2,4)    // Returns "cd"
s.slice(4)      // Returns "efg"
s.slice(3,-1)   // Returns "def"
s.slice(3,-2)   // Returns "de"
s.slice(-3,-1)  // Should return "ef"; returns "abcdef" in IE 4

Bugs

Negative values for start do not work in JScript 3.0 (Internet Explorer 4). Instead of specifying a character position measured from the end of the string, they specify character position 0.

See Also

Array.slice( ), String.substring( )

String.split( )break a string into an array of stringssplit() methodString object

Availability

JavaScript 1.1; JScript 3.0; ECMAScript v1; enhanced in ECMAScript v3

Synopsis

string.split(delimiter, limit)

Arguments

delimiter
The string or regular expression at which the string splits. The use of a regular expression as a delimiter is standardized by ECMAScript v3 and implemented in JavaScript 1.2 and JScript 3.0; it is not implemented in JavaScript 1.1.

limit
This optional integer specifies the maximum length of the returned array. If specified, no more than this number of substrings will be returned. If not specified, the entire string will be split, regardless of its length. This argument is standardized by ECMAScript v3 and implemented in JavaScript 1.2 and JScript 3.0; it is not implemented in JavaScript 1.1.

Returns

An array of strings, created by splitting string into substrings at the boundaries specified by delimiter. The substrings in the returned array do not include delimiter itself, except in the case noted below.

Description

The split( ) method creates and returns an array of as many as limit substrings of the specified string. These substrings are created by searching the string from start to end for text that matches delimiter and breaking the string before and after that matching text. The delimiting text is not included in any of the returned substrings, except as noted below. Note that if the delimiter matches the beginning of the string, the first element of the returned array will be an empty string -- the text that appears before the delimiter. Similarly, if the delimiter matches the end of the string, the last element of the array (assuming no conflicting limit) will be the empty string.

If no delimiter is specified, the string is not split at all, and the returned array contains only a single, unbroken string element. If delimiter is the empty string or a regular expression that matches the empty string, the string is broken between each character, and the returned array has the same length as the string does, assuming no smaller limit is specified. (Note that this is a special case since the empty string before the first character and after the last character is not matched.)

We said above that the substrings in the array returned by this method do not contain the delimiting text used to split the string. However, if delimiter is a regular expression that contains parenthesized subexpressions, the substrings that match those parenthesized subexpressions (but not the text that matches the regular expression as a whole) are included in the returned array.

Note that the String.split( ) method is the inverse of the Array.join( ) method.

Example

The split( ) method is most useful when you are working with highly structured strings. For example:

"1:2:3:4:5".split(":");  // Returns ["1","2","3","4","5"]
"|a|b|c|".split("|");    // Returns ["", "a", "b", "c", ""] 

Another common use of the split( ) method is to parse commands and similar strings by breaking them down into words delimited by spaces:

var words = sentence.split(' '); 

See the Section section for details on a special case when delimiter is a single space. It is easier to split a string into words using a regular expression as a delimiter:

var words = sentence.split(/\s+/); 

To split a string into an array of characters, use the empty string as the delimiter. Use the limit argument if you only want to split a prefix of the string into an array of characters:

"hello".split("");     // Returns ["h","e","l","l","o"]
"hello".split("", 3);  // Returns ["h","e","l"] 

If you want the delimiters, or one or more portions of the delimiter included in the returned array, use a regular expression with parenthesized subexpressions. For example, the following code breaks a string at HTML tags and includes those tags in the returned array:

var text = "hello <b>world</b>";
text.split(/(<[^>]*>)/);  // Returns ["hello ","<b>","world","</b>",""] 

Bugs

In Netscape's implementations of JavaScript, when language Version 1.2 is explicitly requested (with the language attribute of a <script> tag, for example), the split( ) method has one special-case behavior: if delimiter is a single space, the method splits the string at spaces but ignores any white space at the beginning and end of the string. See Section 11.6, for further details.

See Also

Array.join( ), RegExp; Chapter 10

String.substr( )extract a substring

Availability

JavaScript 1.2; JScript 3.0; deprecated

Synopsis

string.substr(start, length)

Arguments

start
The start position of the substring. If this argument is negative, it specifies a position measured from the end of the string: -1 specifies the last character, -2 specifies the second-to-last character, and so on.

length
The number of characters in the substring. If this argument is omitted, the returned substring includes all characters from the starting position to the end of the string.

Returns

A copy of the portion of string starting at and including the character specified by start and continuing for length characters, or to the end of the string if length is not specified.

Description

substr( ) extracts and returns a substring of string. It does not modify string.

Note that substr( ) specifies the desired substring with a character position and a length. This provides a useful alternative to String.substring( ) and String.splice( ), which specify a substring with two character positions. Note, however, that this method has not been standardized by ECMAScript and is therefore deprecated.

Example

var s = "abcdefg";
s.substr(2,2);   // Returns "cd"
s.substr(3);     // Returns "defg"
s.substr(-3,2);  // Should return "ef"; returns "ab" in IE 4

Bugs

Negative values for start do not work in JScript 3.0 (IE 4). Instead of specifying a character position measured from the end of the string, they specify character position 0.

See Also

String.slice( ), String.substring( )

String.substring( )return a substring of a string

Availability

JavaScript 1.0; JScript 1.0, ECMAScript v1

Synopsis

string.substring(from, to)

Arguments

from
An integer that specifies the position within string of the first character of the desired substring.

to
An optional integer that is one greater than the position of the last character of the desired substring. If this argument is omitted, the returned substring runs to the end of the string.

Returns

A new string, of length to-from, which contains a substring of string. The new string contains characters copied from positions from to to -1 of string.

Description

String.substring( ) returns a substring of string consisting of the characters between positions from and to. The character at position from is included, but the character at position to is not included.

If from equals to, this method returns an empty (length 0) string. If from is greater than to, this method first swaps the two arguments and then returns the substring between them.

It is important to remember that the character at position from is included in the substring but that the character at position to is not included in the substring. While this may seem arbitrary or counterintuitive, a notable feature of this system is that the length of the returned substring is always equal to to -from.

Note that String.slice( ) and the nonstandard String.substr( ) can also be used to extract substrings from a string.

Bugs

In Netscape's implementations of JavaScript, when language Version 1.2 is explicitly requested (with the language attribute of a <script> tag, for example), this method does not correctly swap its arguments if from is greater than to. Instead it returns the empty string.

See Also

String.charAt( ), String.indexOf( ), String.lastIndexOf( ), String.slice( ), String.substr( )

TypeErrorthrown when a value is of the wrong type TypeError object errorsTypeError object data typesTypeError exceptions

Availability

JavaScript 1.5; JScript 5.5; ECMAScript

Inherits from/Overrides

v3 Inherits from Error

Constructor

new TypeError( )
new TypeError(message)

Arguments

message
An optional error message that provides details about the exception. If specified, this argument is used as the value for the message property of the TypeError object.

Returns

A newly constructed TypeError object. If the message argument is specified, the Error object will use it as the value of its message property; otherwise, it will use an implementation-defined default string as the value of that property. When the TypeError( ) constructor is called as a function, without the new operator, it behaves just as it does when called with the new operator.

Properties

message
An error message that provides details about the exception. This property holds the string passed to the constructor, or an implementation-defined default string. See Error.message for details

name
A string that specifies the type of the exception. All TypeError objects inherit the value "TypeError" for this property.

Description

An instance of the TypeError class is thrown when a value is not of the type expected. This happens most often when you attempt to access a property of a null or undefined value. It can also occur if you invoke a method defined by one class on an object that is an instance of some other class or if you use the new operator with a value that is not a constructor function, for example. JavaScript implementations are also permitted to throw TypeError objects when a built-in function or method is called with more arguments than expected. See Error for details about throwing and catching exceptions.

See Also

Error, Error.message, Error.name

URIErrorthrown by URI encoding and decoding methods URIError object errorsURIError object

Availability

JavaScript 1.5; JScript 5.5; ECMAScript v3 Inherits from Error

Constructor

new URIError( )
new URIError(message)

Arguments

message
An optional error message that provides details about the exception. If specified, this argument is used as the value for the message property of the URIError object.

Returns

A newly constructed URIError object. If the message argument is specified, the Error object will use it as the value of its message property; otherwise, it will use an implementation-defined default string as the value of that property. When the URIError( ) constructor is called as a function without the new operator, it behaves just as it does when called with the new operator.

Properties

message
An error message that provides details about the exception. This property holds the string passed to the constructor, or an implementation-defined default string. See Error.message for details.

name
A string that specifies the type of the exception. All URIError objects inherit the value "URIError" for this property.

Description

An instance of the URIError class is thrown by decodeURI( ) and decodeURIComponent( ) if the specified string contains illegal hexadecimal escapes. It can also be thrown by encodeURI( ) and encodeURIComponent( ) if the specified string contains illegal Unicode surrogate pairs. See Error for details about throwing and catching exceptions.

See Also

Error, Error.message, Error.name



Library Navigation Links

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