This reference will cover Javascript numeric literals and objects as
well as the default Javascript Operators which manipulate those numbers.
All numbers in Javascript are 64bit (8 bytes) floating point numbers
which yields an effective range of 5e-324 (negative) to
1.7976931348623157e+308 (positive) at the time this article was written
(this may eventually change to 128 bits in the future as 64 bit
processors become commonplace and the ECMA standards evolve).
Integers are considered reliable (numbers without a period or
exponent notation) to 15 digits (9e15)
[1]. Floating point numbers are considered only
as reliable as possible and no more! This
is an especially important concept to understand for currency
manipulation as 0.06 + 0.01 resolves to 0.06999999999999999 instead of
0.07.
If you attempt to work with numbers outside of the generous range
provided by Javascript, Javascript will return a special constant of
either -Infinity or Infinity, representing a negative or positive
overflow, respectively. [-]Infinity is a special reserved keyword in
Javascript like NaN (not a number), or undefined. It can behave as both
a value or a string, that is Infinity
a
and Infinity are equivalent. You can also test for infinity with the Number
object's Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY property.
Division by zero also generates an infinity result.
The ability of Javascript to handle Octal and Hexadecimal numbers is
a relatively new feature of the language and so it's not universally
supported. However, as each day passes this ability becomes more and
more reliable as older browsers are upgraded. If you are coding for a
corporate Internet where you can ensure a base version level (Firefox
1.5 or higher, IE 5.5 or higher) this functionality should be considered
safe.
Numeric constants are considered octal if they are preceded by a
zero, and are considered hexadecimal if they are preceded by a zero and
and x
(0x). This is only for the purpose of the initial
evaluation, Javascript converts octal and hexadecimal numbers into base
ten decimal as the script is evaluated.
You should never precede a number with a zero unless you are
specifically looking for an octal conversion!
Since Javascript stores all numbers as base ten decimals, you'll need
to use the toString()
method of the number to convert the number
into a base other than 10. Unfortunately, the toString()
method
does not create the leading zero for octal numbers or the leading 0x for
hexadecimal numbers so you'll need to add those manually if you want to
be able to further work with the numbers. Simply specify the base of the
number you want as the first argument, 16 for hexadecimal and 8 for
octal. You can even specify 2 for binary.
+,-,*,/,% can also be expressed as +=, -=, *=, /=, %=.
Special Note on Addition (+): The plus sign indicates addition,
unfortunately in Javascript it also represents concatenation so you
should be extremely mindful of where and how you use this operator. Once
your number has become concatenated with a string all further operations
represent concatenation and not addition as you can see in the following
example.
Here, Javascript does addition up to the string where the result of
that addition (14) is concatenated with the string, however the second
set of numbers is treated as concatenation and NOT addition resulting in
an entierly different, and unexpected result. You can correct this by
enclosing the second set of numbers in parenthesis.
The plus sign can also be used to indicate a positive number when
defining a constant. For this purpose the + sign is effectively ignored.
The + sign will not convert a negative number to a positive number in
the same manner as a minus sign.
Special Note on Subtraction (-): The minus sign can also convert
positive numbers to negative numbers and negative numbers to positive
numbers. x=-y is visual sugar for x=(y*-1).
Special Note on Increment/Decrement (++/--): The double-plus and
double-minus indicate the increment (or decrement) by one of the number.
For instance.
The increment/decrement operator can be either before the variable or
after. If the operator is before the variable, the increment/decrement
happens before anything else. If the operator happens after the variable
the increment/decrement happens after everything else has been
evaluated. For instance.
Bitwise operations are a bit of a hack in Javascript. Since all
numbers in Javascript are floating point, and bitwise operators only
work on integers, Javascript does a little behind the scenes magic to
make it appear bitwise operations are being applied to a 32bit signed
integer.
Specifically, Javascript takes the number you are working on and
takes the integer portion of the number. It then converts the integer to
the most number of bits that number represents, up to 31 bits (1 bit for
the sign). So 0 would create a two bit number (1 for the sign, and 1 bit
for 0), likewise 1 would create two bits. 2 would create a 3 bit number,
4 would create a 4 bit number, etc…
It's important to realize that you're not guaranteed a 32bit number,
for instance running not on zero should, in theory, convert 0 to
4,294,967,295, instead it will return -1 for two reasons, the first
being that all numbers are signed in Javascript so not
always
reverses the sign, and second Javascript couldn't make more than one bit
from the number zero and not zero becomes one. Therefore ~0=-1.
(*) When shifting right, double greater-thans (>>) will fill the new
bits to the far left as 1s if the number was negative and zero if the
number was positive. tripple greater-thans (>>>) is the same as double
greater-thans but the fill bit will always be zero so the sign of the
original number is not preserved and the result is always positive.
With the exception of the bitwise NOT operator (~), all operators can
be expressed as (operator)= when working with the same number as the
variable.
One of the most common mistakes in Javascript is to use a bitwise
operator in the place of a logical operator. For instance comparing two
variables is expressed with the logical operator (&&), using a single &
instead of a double && can yield unintended results. To avoid
confusion you should always wrap bitwise operations in
parenthesis to ensure it is not considered a logical evaluation!
Be careful of leading zeros in your string! If the string begins with
0x the number is ASSUMED to be hexadecimal (base 16), and if the string
begins with just 0, the number is ASSUMED to be octal if no radix is
specified. For this reason it is recommended you ALWAYS specify a radix
of 10 unless you specifically need another radix.
parseInt performs no rounding, any digits after the decimal point (if
any) are simply discarded. If the first character can not be converted
to a digit parseInt will return NaN. parseInt will read from the first
character to the first non-numerical character (not 01234567889).
This function is similar to parseInt however it will correctly parse
past the decimal point as well as accepting exponents. Unlike parseInt
you can not specify a base or radix, the number will be pased as base 10
only. parseFloat performs no rounding. If the first character can not be
converted to a digit, parseFloat will return NaN. parseFloat will read
from the first character to the first non-numerical digit (not
0123456789.+-eE)
If Javascript is unable to perform an operation on a number, many
Javascript methods and operators will return NaN, a special reserved
word indicating the result was Not a Number
.
NaN evaluates as FALSE in boolean expressions, however zero also
evaluates as false so if you really want to avoid isNaN you can do a
boolean evaluation as long as you also check for zero.
For consistancy, Javascript provides a Number object. For the most
part, you will not need to define numbers as objects and there are quite
a few reasons why you should not use numbers as a Number object. For
instance…
Although literals are not objects, all of the methods in the Number
object are available to literals because Javascript will temporarily
copy numeric literals to an object in order to execute the desired
method. Thus any prototypes you add to the Number object become
available to all literal objects.
An additional quirk of the Number object is that the properites are
available only through the Number object itself and not through child
objects. Methods are available to all objects and literals.
The following are the properties for the Number object. These
properties are available ONLY to the Number object itself and not any
children or literals.
These properties are, effectively, constants. Importantly, they are a
way to future-proof your Javascript. For instance, if, at some point in
the future, Javascript migrates to 128 bit numbers instead of 64 bit
numbers, the new minimum and maximum values will be reflected in
MAX_VALUE and MIN_VALUE. If the error values of NaN or Infinity ever
change they will be reflected in NaN, NEGATIVE_INFINITY, and
POSITIVE_INFINITY. So wherever possible you should use these constants
instead of hard coding the present values into your code. To test for
NaN you should use the isNaN() function since NaN is always unequal to
itself.
There are only a few methods for the Number object most mathematical
functionality has been moved to the Math object. The big catch with
toExponential, toFixed, and toPrecision is that they are fairly modern
constructs not supported in Mozilla until Firefox version 1.5 (although
IE supported the methods since version 5.5). While it's mostly safe to
use these methods, older browsers WILL break so if you are writing a
public program it's recommended you provide your own prototypes to
provide functionality for these methods for older browser.
This method will return a string representation of the number as an
exponent. If you provide a number in the first argument, this method
will return only the specified number of decimal places.
If you are using a numeric literal (IE not a variable) then you
should provide a space between the number and the method. If your number
has no decimal you can also add one before calling the method.
Supported since: IE 1.5, Firefox 1.5.
This method attempts to return a string representation of the number
as a non-exponent with [digits] numbers after the decimal. Its intention
was to make it easier to work with Currency in Javascript, unfortunately
it was introduced in Mozilla only with Firefox 1.5 and worse, IE 5.5
implemented a buggy version. IE 6 and Firefox 1.5 and higher can use
this method reliably. For older versions you should provide your own
methods.
[Digits] can be a number from zero to twenty, if a number outside
this range is passed toFixed will return a RangeError
. If no
value is passed for [digits] a zero is assumed. The value is rounded up
if the truncated digits evaluated greater than or equal to 5. So 123.456
would output 123.46.
Supported since: IE 1.5, Firefox 1.5.
This method is similar to toString([base]) with the exception that it
attempts to format the number to meet the various regional preferences
for displaying numbers. Unlike toString, toLocaleString() does not
accept a base (so you can't specify base 16 to convert the number to
hexadecimal).
This method will return a string with [precision] digits after the
decimal point. Precision must be a value greater than 0. If no Precision
value is passed, this method behaves like toString(). Like toFixed, this
method will round up to the next nearest number.
Supported since: IE 5.5, Firefox 1.5.
Since Firefox version 1.5, all Javascript objects have a toSource()
method which return the source-code equivalent of the object. This is
extremely useful for creating JSON objects since you can easily turn
objects, strings, arrays, and other data types into JSON data that can
quickly be sent to the server. Unfortunately, only Firefox supports this
method so its usefulness is limited only to office Intranets that have
standardized on Firefox and volunteered to lock themselves into that
platform for all time, no matter what).
Supported since: Firefox 1.5 (Firefox specific method).
The toString method outputs the number as a string. What is VERY
useful and, more-often-than-not, overlooked is that you can pass the
base or radix you would like the number to be displayed as. For instance
passing a [base] of 16 will output the number as hexadecimal. A base of
8 will output the number as octal. A base of 2 will output the number as
binary. (Note that this method will not place a leading zero in front of
octal numbers or 0x
in front of hexadecimal numbers).
If toString is passed without an argument, [base] will default to 10
(standard decimal).
This method simply returns the number as a string. Unlike the
toString() method, valueOf does not allow you to base conversions. The
string output is always equal to the number as it's represented in base
10.
Javascript Strings are deceptively complex constructs. There are actually
two different types of strings --
String Literals
and
String
Objects
-- and they both behave somewhat differently even while trying
to masquerade as the other. Strings, in addition to having some pretty
funky methods of dubious usefulness, have a great many oversights and
shortcomings which can be smoothed over with a few prototypes.
This reference will cover the difference between String Literals and
String Objects, Strings' properties and methods, some common and practical
uses of Strings (particularly in regards to JSON and AJAX), and offer a
few, useful prototypes to extend the String class.
Literal or Object?
There are two different types of Strings and the behave quite
differently. A literal is created just by using quotes around your string.
An object is created by implicit use of the new
keyword. If you
assign a string to a variable using the String
keyword, without the
new
keyword the contents of the parenthesis will be cast as a
string literal.
var StringLiteral = "This is a string Literal";
StringObject = new String("This is a string object");
StringTest = String(12345.68);
document.writeln(typeof(StringLiteral)+'<BR>'); // Outputs: string
document.writeln(typeof(StringObject)+'<BR>'); // Outputs: object
document.writeln(typeof(StringTest)+'<BR>'); // Outputs: string
A string literal has access to all of a string's objects and methods
because javascript will temporarily cast a string literal as a string
object in order to run the desired method.
var StringLiteral = "This is a string Literal";
StringObject = new String("This is a string object");
StringLiteral = StringLiteral.concat('!!!');
StringObject = StringObject.concat('###');
document.writeln(StringLiteral+'<BR>'); // Outputs: This is a string Literal!!!
document.writeln(StringObject+'<BR>'); // Outputs: This is a string object###
Where the two differ is their treatment of new properties and methods.
Like all Javascript Objects you can assign properties and methods to any
String object.
var alpha = new String("This is the first String Object");
var beta = new String("This is a second String Object");
var delta = "This is a String Literal";
alpha.property1 = 'This is private to alpha';
alpha.display = function () {
document.writeln('String: '+this+'<BR>');
document.writeln('Property: '+this.property1+'<BR>');
}
alpha.display();
// Outputs:
// String: This is the first String Object
// Property: This is private to alpha
beta.display();
// Generates an error since we never gave beta any
// properties or methods.
delta.display();
// Generates an error since we never gave the String
// prototype any properties or methods.
You can not add properties or methods to a string literal. They are
ignored by the interpreter.
var alpha = "This is a string literal!";
alpha.property1 = 10;
alpha.method1 = function() { document.writeln('hello world!'); }
document.writeln(alpha.property1+'<BR>'); // outputs: undefined
alpha.method1(); // Generates an error.
The reason you can't add properties or methods to a string literal is
that when you try to access a literal's property or method, the Javascript
interpreter temporarily copies the value of the string into a new object
and then use that object's properties or methods. This means a String
literal can only access a string's default properties or methods and those
that have been added as prototypes.
var alpha = new String("This is Ist String Object");
var beta = new String("This is a second String Object");
var delta = "This is a String Literal";
String.prototype.property1 = 'This is public to all Strings Objects Or Literals';
String.prototype.display = function () {
document.writeln('String: '+this+'<BR>');
document.writeln('Property: '+this.property1+'<BR>');
}
alpha.display();
// Outputs:
// String: This is the first String Object
// Property: This is public to all Strings Objects Or Literals
beta.display();
// Outputs:
// String: This is the second String Object
// Property: This is public to all Strings Objects Or Literals
delta.display();
// Outputs:
// String: "This is a String Literal"
// Property: This is public to all Strings Objects Or Literals
A final caveat is that literals and objects are treated differently by
the eval statement.
var alpha = "2 + 2"; // alpha is a string literal
var beta = new String("2 + 2"); // beta is a string object
document.writeln(eval(alpha)+'<br>'); // Outputs: 4
document.writeln(eval(beta)+'<br>'); // Outputs: 2+2
document.writeln(eval(beta.valueOf())+'<br>'); // Outputs: 4
Strings Are Passed To Functions As Values
Unlike true objects and arrays, all strings (Literal or Objects) are
passed to functions as values which means anything you do to the string
inside the function does not affect the original value.
var alpha = "This is a string literal";
beta = new String("This is a string object");
function changeString(strlit, strobj) {
var strlit='changed!!!';
var strobj='changed!!!';
}
changeString(alpha, beta);
document.writeln(alpha+'<br>'); // Outputs: This is a string literal
document.writeln(beta+'<br>'); // Outputs: This is a string object
Casting A String
You can cast data as a String through the use of the String
command. When used in this way, the String returns the content's
valueOf
result which is always a string. Additionally you can use the
plus sign to append a null string to the object, thus casting it as a
string.
var numString = String(1234.36);
var numArray = String([1,2,3,4,5]);
var numObject = String({'color':'blue', 'song' : 'sung'});
var numString2= 1234.36 + '';
document.writeln(typeof(numString) + ' - ' + numString + '<br>');
document.writeln(typeof(numArray) + ' - ' + numArray + '<br>');
document.writeln(typeof(numObject) + ' - ' + numObject + '<br>');
document.writeln(typeof(numString2) + ' - ' + numString2 + '<br>');
// outputs:
// string - 1234.36
// string - 1,2,3,4,5
// string - [object Object]
// string - 1234.36
As you can see, casting an Object as a String returns an unexpected
result. In Firefox you can get around this with the Object's toSource()
method, however this is not supported by Microsoft's Internet Explorer or
Opera.
var numObject = String({'color':'blue', 'song' : 'sung'}.toSource());
document.writeln(typeof(numObject) + ' - ' + numObject + '<br>');
//outputs (in Firefox):
//({color:"blue", song:"sung"})
// Generates an Error in Microsoft and Opera
String Properties
All strings have a length property which return the length of the
string.
alpha = "abcdefghijklmnopqrstuvwxyz";
beta = new String("abcdefghijklmnopqrstuvwxyz");
document.writeln(alpha.length+'<br>'); // Outputs: 26
document.writeln(beta.length+'<br>'); // Outputs: 26
String Method Reference
General Methods
The following methods are a part of the String object and are available
to String literals as well. As you move the mouse over each row it will be
highlighted to make it easier to read the table. If you click on a method
you will be taken to that method's detailed instructions.
| Method |
IE Version |
Mozilla Version |
Notes |
| charAt |
3.0 |
2.0 |
Returns the character at index. |
| charCodeAt |
5.5 |
4.5 |
Returns the Unicode Value. |
| concat |
4.0 |
4.0 |
Joins Strings |
| fromCharCode |
4.0 |
4.0 |
Creates a string from the supplied unicode integers. |
| indexOf |
3.0 |
2.0 |
Finds position of a substring. |
| lastIndexOf |
3.0 |
2.0 |
Finds position of a substring. |
| localeCompare |
5.5 |
??? |
Compares two strings. |
| replace |
4.0 |
4.0 |
Replaces a substring within a string. |
| slice |
3.0 |
2.0 |
Extracts a substring starting at the index. |
| split |
4.0 |
3.0 |
Returns an array with the delimiter as the pivot. |
| substr |
3.0 |
2.0 |
Extracts x characters of a String starting at Index |
| substring |
3.0 |
2.0 |
Extracts a substring from index to ending Index |
| toLocaleLowerCase |
5.5 |
??? |
Converts a language-localized string to lower case |
| toLocaleUpperCase |
5.5 |
??? |
Converts a language-localized string to upper case |
| toLowerCase |
3.0 |
2.0 |
Converts the string to lower case |
| toString |
--- |
4.5 |
Returns the String Object as a String |
| toString |
4.0 |
3.0 |
Returns the String Object as a String |
| toUpperCase |
3.0 |
2.0 |
Converts the string to upper case |
| valueOf |
4.0 |
3.0 |
See toString() |
String Method Reference (Regular Expressions)
These methods use regular expressions to do search and replace on
strings. In general, methods exist above which allow you to do without
regular expression methods, however if you're familiar with regular
expressions you'll find these methods to be quick and easy (and in some
cases, a whole new can of worms/bugs). These methods are available to all
strings be they Objects or Literals.
| Method |
IE Version |
Mozilla Version |
Notes |
| match |
4.0 |
4.0 |
Does a pattern search on a string. |
| replace |
4.0 |
4.0 |
Replaces a substring within a string. |
| search |
4.0 |
4.0 |
Searches for a pattern within a string. |
String Method Reference (HTML wrappers)
These methods aren't very useful since only a trivial few HTML tags are
supported. It's like someone started doing these then decided they were
silly (which, for the most part, they are) and stopped, but left what they
had already done in interpreter where they became a part of the language.
These methods are available to all Strings whether Objects or Literals.
| Method |
IE Version |
Mozilla Version |
Notes |
| anchor |
3.0 |
2.0 |
Creates an Anchor Tag for the string. |
| big |
3.0 |
2.0 |
Wraps the string in HTML <big> tags. |
| b |
3.0 |
2.0 |
Wraps the string in HTML <b> tags. |
| bold |
3.0 |
2.0 |
Wraps the string in HTML <b> tags. |
| fixed |
3.0 |
2.0 |
Wraps the string in HTML <tt> tags. |
| fontcolor |
3.0 |
2.0 |
Wraps the string in HTML <font color='{color}'> tags. |
| fontsize |
3.0 |
2.0 |
Wraps the string in HTML <font size='{size}'> tags. |
| italics |
3.0 |
2.0 |
Wraps the string in HTML <i> tags. |
| link |
3.0 |
2.0 |
Creates a hypertext link from the string. |
| small |
3.0 |
2.0 |
Wraps the string in HTML <small> tags. |
| strike |
3.0 |
2.0 |
Wraps the string in HTML <strike> tags. |
| sub |
3.0 |
2.0 |
Wraps the string in HTML <sub> tags. |
| sup |
3.0 |
2.0 |
Wraps the string in HTML <sup> tags. |
String.anchor(nameAttribute)
This method creates an anchor attribute for the string. You supply an
index value and the method will return a HTML string, leaving the original
string untouched.
var myString = "Table of Contents";
var htmlString=myString.anchor("TOC");
// htmlString = <A NAME="TOC">Table of Contents</A>
Supported Since IE 3.0, Netscape 2.0
String.big()
This method wraps the string in the HTML big
tag (Big Text).
var myString = "Table of Contents";
var htmlString=myString.big();
// htmlString = <big>Table of Contents</big>
Supported Since IE 3.0, Netscape 2.0
String.b()
This method wraps the string in the HTML b
tag. This
actually exists! I am not making this up!
var myString = "Table of Contents";
var htmlString=myString.b();
// htmlString = <b>Table of Contents</b>
Supported Since IE 3.0, Netscape 2.0
String.bold()
This method wraps the string in the HTML <b> (bold) tag.
var myString = "Table of Contents";
var htmlString=myString.bold();
// htmlString = <b>Table of Contents</b>
Supported Since IE 3.0, Netscape 2.0
String.charAt(Index)
This method returns the character at a specific index starting with
zero. If a string has a length of 26 then charAt's range is 0-25. Note
that Firefox and Opera can achieve the same result with the use of
brackets, treating the string as a simulated array. Be warned, however,
that addressing the string as an Array will return undefined
in
Microsoft Internet Explorer. If you ask for a value which is out of range
(the 53rd position of a string that's
only 26 characters long for instance) this method will return an empty
string (''), which is NOT the same as null. (test for an empty string, not
null).
alpha = "abcdefghijklmnopqrstuvwxyz";
beta = new String("abcdefghijklmnopqrstuvwxyz");
document.writeln(alpha.charAt(3)+'<br>'); // Outputs: d
document.writeln(beta.charAt(3)+'<br>'); // Outputs: d
document.writeln(alpha[3]+'<br>'); // Outputs: d, undefined in IE
document.writeln(beta[3]+'<br>'); // Outputs: d, undefined in IE
// Position out of range return an empty string.
document.writeln(alpha.charAt(53)+'<br>'); // Outputs: ''
document.writeln(beta.charAt(53)+'<br>'); // Outputs: ''
Supported Since IE 3.0, Netscape 2.0
String.charCodeAt(Index)
This method returns the Unicode value of the character at the requested
index. This method works the same as charAt() but instead of a character
it returns a number representing the Unicode value of the character. In
very ancient versions of Javascript -- Netscape 4.0 and less, Internet
Explorer 5.0 and less -- this number represented the ISO-Latin-1 character
set rather than Unicode, however, the percentage of these browsers still
in use today are so small it's considered safe to assume a Unicode result.
If you request an index which doesn't exist, Javascript returns NaN
(Not a Number, which is a Javascript reserved word/value in the same vein
as null and undefined).
alpha = "abcdefghijklmnopqrstuvwxyz";
beta = new String("abcdefghijklmnopqrstuvwxyz");
document.writeln(alpha.charAt(3)+'<br>'); // Outputs: 100
document.writeln(beta.charAt(3)+'<br>'); // Outputs: 100
// Position out of range return an empty string.
document.writeln(alpha.charAt(53)+'<br>'); // Outputs: NaN
document.writeln(beta.charAt(53)+'<br>'); // Outputs: Nan
Supported Since IE 5.5, Netscape 4.5
String.concat(String[, String[, String...]])
The concat method joins the supplied strings to the original, returning
a new string as a result. You can also use the plus sign (+) to achieve
the same effect. There is no difference between string Objects and String
Literals in the following example.
var alpha = " String 1 ";
var beta = " String 2 ";
var delta = " String 3 ";
newString1 = alpha + beta + delta;
newString2 = alpha.concat(beta, delta);
alpha += beta + delta;
document.writeln(newString1+'<br>'); // outputs: String 1 String 2 String 3
document.writeln(newString2+'<br>'); // outputs: String 1 String 2 String 3
document.writeln(alpha+'<br>'); // outputs: String 1 String 2 String 3
Numbers will be cast as strings for the concatenation. When using + to
join strings, ANY string in the equation will do a string concatenation on
all the items which follow. That's a bit confusing but say we have
5+20+42+"string", then the result will become 67 String
, so we did
straight addition upto the string. AFTER the string, every addition
becomes a string concatenation so 5+20+42+" string "+20+5 becomes 67
String 205
. The second part of the equation becomes string
concatenation so 20 is appended with 5 instead of having 5 added to 20.
var alpha = "35";
var beta = 60;
newString1 = alpha + beta;
newString2 = alpha.concat(beta);
alpha += beta;
delta = 5+20+42+" String "+10+5;
document.writeln(newString1+'<br>'); // Outputs 3560
document.writeln(newString2+'<br>'); // Outputs 3560
document.writeln(alpha+'<br>'); // Outputs 3560
document.writeln(delta+'<br>'); // Outputs 67 String 105
Supported Since IE 4.0, Netscape 4.0
String.fixed()
This method wraps the string in the HTML tt
tag (fixed-pitch
font).
var myString = "Table of Contents";
var htmlString=myString.fixed();
// htmlString = <tt>Table of Contents</tt>
Supported Since IE 3.0, Netscape 2.0
String.fontcolor(color)
This method wraps the string in the HTML <font color='{color}'> tag.
Note that this method violates Javascript's camelCase naming convention.
fontcolor() is all lower case instead of fontColor().
var myString = "Table of Contents";
var htmlString = myString.fontcolor('blue');
// htmlString = <font color="blue">Table of Contents</font>
Supported Since IE 3.0, Netscape 2.0
String.fontsize(size)
This method wraps the string in the HTML <font size='{size}'> tag. Note
that this method violates Javascript's camelCase naming convention.
fontsize() is all lower case instead of fontSize().
There's a bit of funkiness here. If you use an integer as the size, you
specify a size as one of 7 base sizes. If you use a string as the integer,
the size becomes relative to the <basefont> tag.
var myString = "Table of Contents";
var htmlString = myString.fontsize(7);
// htmlString = <font size="12">Table of Contents</font>
Supported Since IE 3.0, Netscape 2.0
String.fromCharCode(code1[, code#...])
This method accepts a series of Unicode characters and converts them to
a Javascript string. This method is a bit unusual in that its really more
of a function than a String method since it doesn't act on the data
contained in the string. Because of this you don't need to use a string to
access this method, you can simply use the String object itself. Prior to
IE 4.0 and Netscape 4.0, this function converted ISO-Latin-1 codes.
var test = String.fromCharCode(112, 108, 97, 105, 110);
document.writeln(test); // outputs: plain
Supported Since IE 4.0, Netscape 4.0
String.indexOf(SearchValue[, startIndex])
IndexOf returns an index where the passed SearchValue was found or -1
if the search value was not found. You can also supply an optional
starting index (StartIndex) where the method will start its search.
var alpha = 'The brown fox was faster than the white fox.';
var beta = new String('The brown fox was faster than the white fox.');
document.writeln(alpha.indexOf('fox')+'<br>'); // Outputs 10;
document.writeln(beta.indexOf('fox')+'<br>'); // Outputs 10;
// Now we'll start looking after the first position and get the second.
document.writeln(alpha.indexOf('fox',11)+'<br>'); // Outputs 40;
document.writeln(beta.indexOf('fox',11)+'<br>'); // Outputs 40;
// Look for something which isn't there.
document.writeln(beta.indexOf('bear')+'<br>'); // Outputs -1;
Supported Since IE 3.0, Netscape 2.0
String.italics()
This method wraps the string in the HTML i
tag (italics).
var myString = "Table of Contents";
var htmlString=myString.italics();
// htmlString = <i>Table of Contents</i>
Supported Since IE 3.0, Netscape 2.0
String.lastIndexOf(SearchValue[, startIndex])
This method is the same as the indexOf method, however it searches from
the end of the string to the beginning of the string.
var alpha = 'The brown fox was faster than the white fox.';
var beta = new String('The brown fox was faster than the white fox.');
document.writeln(alpha.lastIndexOf('fox')+'<br>'); // Outputs 40;
document.writeln(beta.lastIndexOf('fox')+'<br>'); // Outputs 40;
// Now we'll start looking after the first position and get the second.
document.writeln(alpha.lastIndexOf('fox',39)+'<br>'); // Outputs 10;
document.writeln(beta.lastIndexOf('fox',39)+'<br>'); // Outputs 10;
// Look for something which isn't there.
document.writeln(beta.lastIndexOf('bear')+'<br>'); // Outputs -1;
Supported Since IE 3.0, Netscape 2.0
String.link(url)
This method creates a hypertext link for the string. You supply a url
as the first argument and the method will return a HTML string, leaving
the original string untouched.
var myString = "Table of Contents";
var htmlString=myString.link("http://www.hunlock.com");
// htmlString = <A HREF="http://www.hunlock.com">Table of Contents</A>
Supported Since IE 3.0, Netscape 2.0
String.localeCompare(string)
This IE specific method is supported by Firefox and Opera (support
elsewhere may be spotty and Opera returns unusual, but usable, results).
This method compares the string with the passed value. If the comparison
string sorts lower than the original string then this method returns 1 (in
opera test for any positive value). If the two strings are equal, this
method returns 0, and if the comparison string sorts higher than the
original string then this method returns -1 (Search for any negative value
in Opera).
Firefox 2.0 supports this method, however it is not documented so it's
not possible to tell when support for this method began. The documentation
indicates that this comparison works regardless of the language being used
(Japanese for instance). Since this is not documented in Firefox, the
localization support may be imperfect.
var str = 'Hello Dolly!';
var result = str.localeCompare('Hello Dolly!');
document.writeln(result+'<br>'); // Outputs: 0
var result = str.localeCompare('Hello Bolly!');
document.writeln(result+'<br>'); // Outputs: 1
var result = str.localeCompare('Hello Molly!');
document.writeln(result+'<br>'); // Outputs: -1
Supported Since IE 5.5, Netscape (unknown, only unofficial support)
String.match(regExp)
The match method uses a regular expression to determine if a substring
exists within the string. If the substring exists it will return the
substring. If you looked for multiple occurrences (/string/g) and more
than one result is found it will return an array containing all the
matches. Match takes 2x (best-case) as long to execute as IndexOf.
str = 'Now is the time for all good men to come to the aid of their country!';
result = str.match(/the/ig); // Look for "the" case insensitive (i), all occurrences (g)
document.writeln(result+'<br>'); // Outputs array: the, the, the
result = str.match(/^now/i); // Look for "now", case insensitive(i), start of string (^)
document.writeln(result+'<br>'); // Outputs array: Now
// Here we look for something that's not there -- "the" as the start of the string
// the result is null which means result will evaluate to false if we do...
// if not(result) { alert('we found nothing!'); }
result = str.match(/^the/i); // Look for "the" case insensitive(i), start of string (^)
document.writeln(result+'<br>'); // Outputs array: null
// The next example does pattern matching which, in this case, means we're looking for
// something that looks like a telephone number.
str = "Faith's Number is 867-5309. At least back in the 80's";
result = str.match(/\d{3}-\d{4}/); // Search for 3 digits, dash, 4 digits
document.writeln(result+'<br>'); // Outputs: 867-5309
Supported Since IE 4.0, Netscape 4.0
String.replace(regExp/substr, replacementValue[, flags])
This is one of String's more complex methods, and correspondingly, one
of the most powerful. At its most simplest, this method will look for the
supplied substring and, if found, replace it with the supplied replacement
string. The result of the replacement is returned as a new string. The
original string remains untouched.
str = "Faith's Number is 867-5309. At least back in the 80's. The 80's were cool.";
result = str.replace("Faith's", "Bob's"); // Replace Faith's With Bob's
document.writeln(result);
// outputs:
//Bob's Number is 867-5309. At least back in the 80's. The 80's were cool.
This example works on a direct match. If we forgot to capitalized the J
in Jenny, the replace would fail.
str = "Faith's Number is 867-5309. At least back in the 80's. The 80's were cool.";
result = str.replace("Faith's", "Bob's"); // Replace Faith's With Bob's
document.writeln(result);
// outputs:
//Faith's Number is 867-5309. At least back in the 80's. The 80's were cool.
(firefox only) If we would like to ignore the case of the original
string we can specify an optional flag . The flags are...
- g -- global, match more than one occurrence.
- i -- case insensitive
- m -- match over multiple lines ( useful for <pre> text. )
Here we'll supply an i flag so the previous example will work.
str = "Faith's Number is 867-5309. At least back in the 80's. The 80's were cool.";
result = str.replace("Faith's", "Bob's", "i"); // Replace J/Faith's With Bob's
document.writeln(result);
// outputs:
//Bob's Number is 867-5309. At least back in the 80's. The 80's were cool.
If you would like to use the flags outside of Firefox you'll need to
convert the search string to a regular expression. This is actually pretty
easy. Instead of using quotes, use forward slashes, and at the end of the
expression simply append the flags you would like the flag to use. In our
above example…
result = str.replace("Faith's", "Bob's", "i"); // Replace J/Faith's With Bob's
…becomes…
result = str.replace(/Faith's/i, "Bob's"); // Replace J/Faith's With Bob's
In this next example we'll replace the
with ***
. Note
that only the first occurrance will be replace in the first example, but
in the second, since we added a g
flag (in addition to i
)
both occurrences of the
will be replaced.
str = "Faith's Number is 867-5309. At least back in the 80's. The 80's were cool.";
result = str.replace(/the/i, "***"); // Replace "the" with "***", case insensitive
document.writeln(result);
// outputs:
//Faith's Number is 867-5309. At least back in *** 80's. The 80's were cool.
str = "Faith's Number is 867-5309. At least back in the 80's. The 80's were cool.";
result = str.replace(/the/ig, "***"); // Replace "the" with "***", case insensitive
document.writeln(result);
// outputs:
//Faith's Number is 867-5309. At least back in *** 80's. *** 80's were cool.
If you opt to use a regular expression then you need to specify your
flags as regular expresion modifiers instead of passing them as arguments.
In Firefox, if you specify a regular expression, it will ignore the
flags
arguments and instead look for the flags as part of the regular
expression's modifier.
A more powerful and practical example of a regular expression replace
looks for something resembling a telephone number and masks it out with #
signs. The following example matches all 3 digit, dash, 4 digit patterns
and replaces it with ###-####.
str = " Faith's Number is 867-5309. Back in the 80's. The 80's were cool.";
result=str.replace(/[\d{3}\-\d{4}]+/,'###-####','g');
document.writeln(result);
// outputs:
// Faith's Number is ###-####. back in the 80's. The 80's were cool.
You can use a function as the replacement value. The replace method
will use the return value of your function as the replacement value. It is
unfortunate, but the arguments passed to your function are not well
thought out. If you used strings as your search criteria instead of
regular expressions then the parameters will always be…
function myReplace(matchedSubstring, Index, OriginalString)
matchedSubstring
will be the substring which was found and is
going to be replaced. Index
was the numerical position the
substring was found inside the string. OriginalString
is the full
string that was searched. If you specified a g
flag then your
function will be called each time a match was found.
The unfortunate part referred to earlier is that if you used a regular
expression then parenthical matches will be inserted between the
matchedSubstring and the Index, so there's no constant you can use to
refer to the Index or OriginalString save by using the argument's array,
which needlessly increases the complexity of the function.
Here we'll replace all numbers with either a (if less than or equal to
5) or b (if greater than 5). We're using a regular expression as our
search String, however since we're not using parenthical matches our
function arguments will be constant.
function checkit(matchedSubstring, Index, OriginalString) {
if (matchedSubstring<=5) { return 'a' } else {return 'b'}
}
str = "Faith's Number is 867-5309. At least back in the 80's. The 80's were cool.";
result=str.replace(/\d/g, checkit); // Search for any digits, call checkit for replacement
document.writeln(result);
// outputs:
//Faith's Number is bbb-aaab. At least back in the ba's. The ba's were cool.
Finally, there are some special codes you can use in your replacement
string…
- $$ -- Inserts a dollar sign.
- $& -- Inserts the matched substring
- $` -- Inserts the portion of the string which preceded the match.
- $' -- Inserts the portion of the string which followed the match.
- $n -- Inserts the Nth parenthesized substring match (assuming the
first argument was a regular expression and not a substring)
The following example takes all number groups and wraps them in
brackets using the $& replacement string.
str = "Faith's Number is 867-5309. At least back in the 80's. The 80's were cool.";
result=str.replace(/(\d+)/g,'[$&]','g');
document.writeln(result);
// Outputs:
//Faith's Number is [867-5309]. At least back in the [80]'s. The [80]'s were cool.
Supported Since IE 4.0, Netscape 4.0
String.search(regExp)
This method accepts a regular expression as an argument and returns the
index in the string where the pattern was matched, or -1 if the pattern
could not be matched. If more than one occurrence of the pattern exists,
only the first index will be returned.
This method is similar to indexOf except that it's twice as slow and
doesn't allow more than one item to be matched. So if possible, you should
stick with indexOf.
str = "Once upon a time the big, bad ogre ate the goat, the mistral sang";
result=str.search(/(the)+/ig);
document.writeln(result); // outputs: 17
Supported Since IE 4.0, Netscape 4.0
String.slice(startIndex[, endIndex])
Slice will extract a substring starting at the specified starting index
and ending at the specified ending index. If endIndex is less than or
equal to startIndex, the slice method will return a null string. If
endIndex is not specified the slice Method will extract to the end of the
string.
The original string is untouched.
str = "Faith's Number is 867-5309.";
result = str.slice(8,14); // Contains: Number
result = str.slice(8); // Contains: Number is 867-5309.
result = str.slice(8,3); // Null
result = str.slice(100); // Null
Supported Since IE 3.0, Netscape 2.0
String.small()
This method wraps the string in the HTML <small> (Small Text)tag.
var myString = "Table of Contents";
var htmlString=myString.small();
// htmlString = <small>Table of Contents</small>
Supported Since IE 3.0, Netscape 2.0
String.split(delimiter[, limit])
This is one of the most powerful of the String methods. Given a
delimiter as the first argument, split() will create an array with each
element containing an item separated by the delimiter in the original
string. That's a bit wordy so lets just show you the code…
str = "One~Two~Three~Four~Five";
newArray = str.split('~');
for(i=0; i<newArray.length; i++) {
document.writeln(i+'-'+newArray[i]+'<BR>');
}
// outputs:
// 0-One
// 1-Two
// 2-Three
// 3-Four
// 4-Five
The above example has a string with 5 words separated by the
tilde (~) character. The split breaks the string into
an array using the tilde as the delimiter.
A very real world example is that you can use this method to receive an
array from the server via Ajax. You'll receive the array as a string with
a unique delimiter just like in our example. By running the string through
the split method we have now reconstructed our array as it appears on the
server.
If you would like to manipulate a string as a true array (for speed or
other reasons) then you can easily convert a string to an array and then
back again. To convert each index in a string to its corresponding index
in an Array just use a null string as a delimiter.
str='The quick brown fox';
newArray = str.split('');
for(i=0; i<newArray.length; i++) {
document.writeln(newArray[i]+', ');
}
//outputs:
//T, h, e, , q, u, i, c, k, , b, r, o, w, n, , f, o, x,
And to reverse the process use the Array's join() method with a null
string.
str=newArray.join('');
document.writeln(str);
//outputs:
//The quick brown fox
Using the String method, split() and the Array method, join() you can
easily manipulate strings as arrays. String.split() can convert incoming
AJAX data into arrays, and Array.join can convert a Javascript array into
a string ready to be sent to the server via Ajax (just use a unique
delimiter in your join method instead of a null string, as such…)
toServer=newArray.join('~'); // Creates a string delimitated by tildies (~)
The optional limit
parameter specifies how many array elements
will be made. For instance if you have a 30,000 character string and you
only need the first 100 characters you would use …
newArray = str.split('',100);
Supported Since IE 4.0, Netscape 3.0
String.strike()
This method wraps the string in the HTML <strike> (strikeout
effect) tag.
var myString = "Table of Contents";
var htmlString=myString.strike();
// htmlString = <strike>Table of Contents</strike>
Supported Since IE 3.0, Netscape 2.0
String.sub()
This method wraps the string in the HTML <sub> (subscript)
tag.
var myString = "Table of Contents";
var htmlString=myString.sub();
// htmlString = <sub>Table of Contents</sub>
Supported Since IE 3.0, Netscape 2.0
String.substr(index[, numChars])
The substr() method is similar to the slice() method save that the
second argument indicates how many characters to include instead of an
ending index. If numChars is not a positive number then substr will return
an empty string. If numChars is omitted, then substr will extract a string
from the index to the end of the string.
substr
returns a new string. The original string is left
untouched.
var str='The quick brown fox';
var speed = str.substr(4,5); // contains: quick
var speed = str.substr(4); // contains: quick brown fox
var speed = str.substr(4,-2); // contains: ''
Supported Since IE 3.0, Netscape 2.0
String.substring(index[, stopIndex])
This method is nearly identical to the slice() method. The only real
difference is that if stopIndex is less than index, instead of returning
an empty string, substring() will extract the string from the stopIndex to
the Index (effectively reversing the numbers for you).
result = str.substring(8,14); // Contains: Number
result = str.substring(8); // Contains: Number is 867-5309.
result = str.substring(8,0); // Contains: Faith's
result = str.substring(100); // Null
result = str.substring(100,0); // Contains: Faith's Number is 867-5309.
Supported Since IE 3.0, Netscape 2.0
String.sup()
This method wraps the string in the HTML <sup> (superscript)
tag.
var myString = "Table of Contents";
var htmlString=myString.sup();
// htmlString = <sup>Table of Contents</sup>
Supported Since IE 3.0, Netscape 2.0
String.toLocaleLowerCase()
This method is intended to convert a string to lower case, regardless
of the language being used. Firefox 2.0 can use this method, however it
does not appear in the official documentation indicating that true
international support may be imperfect.
var str = 'AbCdEfGhIjKlMnOpQrStUvWxYz';
var result = str.toLocaleLowerCase();
document.writeln(result); // Outputs: abcdefghijklmnopqrstuvwxyz
Supported Since IE 5.5, Firefox (Unknown. Only unofficial support)
String.toLocaleUpperCase()
This method is intended to convert a string to upper case, regardless
of the language being used. Firefox 2.0 can use this method, however it
does not appear in the official documentation indicating that true
international support may be imperfect.
var str = 'AbCdEfGhIjKlMnOpQrStUvWxYz';
var result = str.toLocaleUpperCase();
document.writeln(result); // Outputs: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Supported Since IE 5.5, Firefox (Unknown. Only unofficial support)
String.toLowerCase()
This method simply returns the string as all lower case. The original
string is left untouched. ( See also: toUpperCase() )
var str = 'AbCdEfGhIjKlMnOpQrStUvWxYz';
var result = str.toLowerCase();
document.writeln(result); // Outputs: abcdefghijklmnopqrstuvwxyz
Supported Since IE 3.0, Netscape 2.0
String.toSource()
This is a Firefox only method which will return a string that can be
used to rebuild the string if passed through an eval statement. Neither
Internet Explorer or Opera support this method.
var str='AbCdEfGhIjKlMnOpQrStUvWxYz';
document.writeln(str.toSource());
// Outputs:
// (new String("AbCdEfGhIjKlMnOpQrStUvWxYz"))
Supported Since Netscape 2.0, Not supported in IE/Opera.
String.toString()
This method overrides the default Object.toString() method. Your use of
this method would be fairly redundant.
strObj = new String("Hello Javascript");
strLit = "Hello World";
document.writeln(strObj.toString()+'<br>'); // Outputs: Hello Javascript
document.writeln(typeof(strObj.toString())+'<br>'); // Outputs: string
document.writeln(strLit.toString()+'<br>'); // Outputs: Hello Javascript
document.writeln(typeof(strLit.toString())+'<br>'); // Outputs: string
Supported Since IE 4.0, Netscape 3.0
String.toUpperCase()
This method simply returns the string as all upper case. The original
string is left untouched. ( See also: toLowerCase() )
var str = 'AbCdEfGhIjKlMnOpQrStUvWxYz';
var result = str.toLowerCase();
document.writeln(result); // Outputs: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Supported Since IE 3.0, Netscape 2.0
String.valueOf()
See String.toString()
Supported Since IE 4.0, Netscape 3.0
Converting Arrays To Strings For Ajax
If you need to send an array to a server through an Ajax call, you'll
need to convert the array to a string before you can do it. This is easy
enough to do with the Array's join() method. Simply pick a unique
character that is unlikely to appear in your array. For this purpose a
tilde (~) is usually a safe character.
var myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
var ajaxStr = myArray.join('~'); // contains: 1~2~3~4~5~6~7~8~9~10~11~12~13~14
You can now send ajaxStr to the server where it can be broken out into
an array again.
Converting Strings into Arrays For Ajax
If you've received a string as an array via Ajax you'll need to convert
that string back into an array in Javascript. This is very simple to do!
Just use the string's split() method to convert the string into the array.
In this example we'll assume the server used the tilde (~) as the
delimiter.
var ajaxStr = "1~2~3~4~5~6~7~8~9~10~11~12~13~14"; // What we got from the server.
var myArray = ajaxStr.split('~'); // Turn the string into an Array
//MyArray now contains: 1,2,3,4,5,6,7,8,9,10,11,12,13,14;
Convert A String To JSON
To convert a string to JSON (Javascript Object Notation), you'll need
to download and include the public domainJSON library at
http://www.json.org/json.js. In addition to giving you a
String.toJSONString() method, it also gives you methods for converting
other data types as well.
Useful Prototypes
While the String methods in Javascript are powerful and useful, there
is still room for improvement and thanks to prototyping you can add
whatever useful features you want!
Useful Prototypes: trim()
Removing leading and trailing whitespace is something which should have
shipped with Javascript from the start, but it's easy enough to make up
for the designer's oversight.
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
return this.replace(/^\s+/g,"");
}
String.prototype.rtrim = function() {
return this.replace(/\s+$/g,"");
}
Usage:
var test = " Test ";
var test1 = test.ltrim(); // returns "Test "
var test2 = test.rtrim(); // returns " Test"
var test3 = test.trim(); // returns "Test"
Useful Prototypes: htmlEntities()
This method escapes all &, <, and > symbols in the string, making it
safe to display the string on a web page without fear that it will be
treated as HTML.
String.prototype.htmlEntities = function () {
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
};
Usage:
var tmp = '<html><head></head>';
var safe= tmp.htmlEntities(); // Returns <html><head></head>
Useful Prototypes: stripTags()
This method will remove all < > tags (and everything in between),
ensuring that the string contains no HTML.
String.prototype.stripTags = function () {
return this.replace(/<([^>]+)>/g,'');
}
Usage:
var tmp = '<a href="http://somespammer.com">Some Link</a>';
var safe= tmp.stripTags(); // Returns: Some Link;
Useful Prototypes: toArray()
This method explodes the string out into an array of characters.
String.prototype.toArray = function() {
return this.split('');
}
Usage¦
var str='AbCdEfGhIjKlMnOpQrStUvWxYz';
var arr=str.toArray();
for (var i=0; i<arr.length; i++) {
document.write(arr[i]+', ');
}
//Outputs:
//A, b, C, d, E, f, G, h, I, j, K, l, M, n, O, p, Q, r, S, t, U, v, W, x, Y, z,
Useful Prototypes: toIntArray()
This method explodes the string out into an array of integers
representing the character's unicode.
String.prototype.toIntArray = function() {
var returnArray = [];
for (var i=0; i<this.length; i++) {
returnArray.push(this.charCodeAt(i));
}
return returnArray;
}
Usage¦
var str='AbCdEfGhIjKlMnOpQrStUvWxYz';
var arr=str.toIntArray();
for (var i=0; i<arr.length; i++) {
document.write(arr[i]+', ');
}
// Outputs:
// 65, 98, 67, 100, 69, 102, 71, 104, 73, 106, 75, 108, 77,
// 110, 79, 112, 81, 114, 83, 116, 85, 118, 87, 120, 89, 122,
Javascript Arrays Explained in Depth
var myArray = [];
You don't need to tell Javascript how many items to size the Array for.
Javascript will automatically increase the size of the Array as needed,
as you add items into the Array. Creating an Array with brackets
instead of with the new
constructor avoids a bit of confusion where
you want
to initialize only one integer. For instance.
var badArray = new Array(10); // Creates an empty Array that's sized for 10 elements.
var goodArray= [10]; // Creates an Array with 10 as the first element.
As you can see these two lines do two very different things. If you had
wanted to add more than one item then badArray would be initialized
correctly since Javascript would then be smart enough to know that you
were initializing the array instead of stating how many elements you
wanted to add. Since the new constructor is not necessary with Arrays
and there's a slight chance of unintended results by using the new
constructor, it's
recommended you not use new Array()
to create an Array.
Initializing An Array
You can initialize your array with pre-defined data…
var myArray = ['January', 'February', 'March'];
document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2>March
You can inizialize your array with data after an empty array has been
created…
var myArray = [];
myArray[0] = 'January';
myArray[1] = 'February';
myArray[2] = 'March';
document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2>March
If you skip an element, the blank
Array elements will be of type
undefined
var myArray = [];
myArray[0] = 'January';
myArray[1] = 'February';
myArray[5] = 'March';
document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2>undefined
document.writeln('3>'+myArray[3]+'<BR>'); // Will output: 3>undefined
document.writeln('4>'+myArray[4]+'<BR>'); // Will output: 4>undefined
document.writeln('5>'+myArray[5]+'<BR>'); // Will output: 5>March
Storing Data In An Array
An array can store anything you can assign to a variable: booleans,
numbers, strings, functions, objects, other Arrays, even regular
expressions…
var myArray = [ 3, 'hello!', function() {return 5}, {'color':'blue', 'budget':25}, /[ell]/i ];
document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>3
document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>hello!
document.writeln('2>'+myArray[2]()+'<BR>'); // Will output: 2>5
document.writeln('3>'+myArray[3].color+'<BR>'); // Will output: 3>blue
document.writeln('3>'+myArray[3].budget+'<BR>'); // Will output: 3>25
document.writeln('4>'+myArray[4].test(myArray[1])+'<BR>'); // Will output: 4>true
Multi-Dimensional Arrays
Since an Array can store other Arrays you can get the benefit of
multi-dimension arrays.
var x=[0,1,2,3,4,5];
var y=[x];
In the above example we created an array named x
and assigned it
as the first element in the array y
. If we ask for the value of
y[0]
it will return the contents of x
as a string because we didn't
specify an index.
var x=[0,1,2,3,4,5];
var y=[x];
document.writeln(y[0]); // Will output: 0,1,2,3,4,5
If we wanted the third index we'd access it this way…
var x=[0,1,2,3,4,5];
var y=[x];
document.writeln(y[0][3]); // Will output: 2
There's no defined limit to how many Arrays you can nest in this
manner. For instance …
document.writeln(bigArray[5][8][12][1])
…would indicate bigArray's 5th index held an array, who's 8th index
held an array, who's 12th index held an array, who's first index contains
the data we want.
Javascript Arrays Are Passed By Reference
Arrays are passed to functions by reference, or as a pointer to the
original. This means anything you do to the Array inside the function
affects the original.
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ];
document.writeln(myArray[1]); // Will output: one
function passedByReference(refArray) {
refArray[1] = 'changed';
}
passedByReference(myArray);
document.writeln(myArray[1]); // Will output: changed
Javascript Arrays Are Assigned By Reference
Assigning an Array to a new variable creates a pointer to the original
Array. For instance…
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ];
var newArray= myArray;
newArray[1] = 'changed';
document.writeln(myArray[1]); // Will output: changed
Passing Arrays As Values
To pass an Array by value instead of by reference, use
the Array.slice() method.
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ];
var newArray= myArray.slice();
newArray[1] = 'changed';
document.writeln(myArray[1]); // Will output: one
function passedByReference(refArray) {
refArray[1] = 'changed';
}
passedByReference(myArray.slice());
document.writeln(myArray[1]); // Will output: one
Array.length
Every Array has a length
property. This always contains the
number of elements in the array. Since Arrays always start at zero, the
length property is convenient for loops since it will always be one
greater than the actual index. For instance if the Array has 10 elements
then the indexes will be 0-9, so as long as our counter is less than
the Array.length we'll cover the entire Array…
for (var i=0; i<myArray.length; i++) {}
Going back to our undefined
example above. Even though 3 of the
Array items are undefined
the length property will still count them
because it's always one higher than the highest accessable index value.
var myArray = [];
myArray[0] = 'January';
myArray[1] = 'February';
myArray[5] = 'March';
document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2>undefined
document.writeln('3>'+myArray[3]+'<BR>'); // Will output: 3>undefined
document.writeln('4>'+myArray[4]+'<BR>'); // Will output: 4>undefined
document.writeln('5>'+myArray[5]+'<BR>'); // Will output: 5>March
document.writeln('Array Length: '+myArray.length); // Will output: Array Length: 6
Array.length is NOT a read-only value,
you can set it as you wish. If you have 100 elements in an array and set
the length to 50, Javascript
will truncate the last 50 elements from the array (effectively deleting
them). If you have 10 elements in an array and set Array.length to 100
then the length of the array will be expanded to 100, creating 90
undefined elements after the original 10 items.
Javascript Does Not Support Associative Arrays
An associative array is an array which uses a string instead of a
number as an index.
var normalArray = [];
normalArray[1] = 'This is an enumerated array';
alert(normalArray[1]); // outputs: This is an enumerated array
var associativeArray = [];
associativeArray['person'] = 'John Smith';
alert(associativeArray['person']); // outputs: John Smith
Javascript does not have, and does not support Associative Arrays.
However… All arrays in Javascript are objects and Javascript's object
syntax gives a basic emulation of an associative Array. For this
reason the example code above will actually work. Be warned that this is
not a real array and it has real pitfals if you try to use it. The
'person' element in the example becomes part of the Array object's
properties
and methods, just like .length, .sort(), .splice(), and all the other
built-in properties and methods.
You can loop through an object's properties with the following loop…
var associativeArray = [];
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";
for (i in associativeArray) {
document.writeln(i+':'+associativeArray[i]+', ');
// outputs: one:First, two:Second, three:Third
};
In the above example, associativeArray.length will be zero because we
didn't actually put anything into the Array, we put it into
associativeArray's
object. associativeArray[0]
will be undefined.
The loop in the above example will also pick up any methods,
properties, and prototypes which have been added to the array and not just
your data.
A lot of problems people have with the Prototype library is that their associative arrays
break because Prototype adds a few useful Prototype
functions to the Array object and for i in x
loops pick up those
additional methods. That's the pitfal of using Array/objects as a poor
man's
associative array.
As a final example, the previous code will work
regardless of
whether you define associativeArray as an Array ([]), an Object({}), a
Regular
Expression (//), String(""), or any other Javascript object.
The bottom line is -- don't try to use associative arrays, code for
what they are -- object properties, not Arrays.
Array Methods Reference
Since Javascript Arrays are modified objects, each and every Array you
create has a few core methods. What's really interesting is that some
of these methods implement basic data structures you'd normally have to
write yourself such as stacks (push, pop) and queues (shift, unshift).
| Method |
IE Version |
Mozilla Version |
Notes |
| concat |
4.0 |
4.0 |
Joins multiple Arrays |
| every |
* |
FF 1.5 |
Calls a function for every element of the array until false is
returned. |
| filter |
* |
FF 1.5 |
Creates an array with each element which evaluates true in the
function provided. |
| forEach |
* |
FF 1.5 |
Executes a specified function on each element of an Array |
| join |
3.0 |
3.0 |
Joins all the Array elements together into a string. |
| indexOf |
* |
FF 1.5 |
Searches the Array for specific elements. |
| lastIndexOf |
* |
FF 1.5 |
Returns the last item in the Array which matches the search
critera. |
| map |
* |
FF 1.5 |
Creates a new array with the result of calling the specified
function on each element of the Array. |
| pop |
5.5 |
4.0 |
Returns the last item in the Array and removes it from the Array. |
| push |
5.5 |
4.0 |
Adds the item to the end of the Array. |
| reverse |
3.0 |
3.0 |
Reverses the Array so the last item becomes the first and
vice-versa. |
| shift |
5.5 |
4.0 |
Returns the first item in the Array and removes it from the Array. |
| slice |
4.0 |
4.0 |
Returns a new array from the specified index and length. |
| some |
* |
FF 1.5 |
Passes each element through the supplied function until true
is returned. |
| sort |
3.0 |
3.0 |
Sorts the array alphabetically or by the supplied function. |
| splice |
5.5 |
4.0 |
Deletes the specified index(es) from the Array. |
| toSource |
--- |
FF 1.5 |
Returns the source code of the array. |
| toString |
3.0 |
3.0 |
Returns the Array as a string. |
| unshift |
5.5 |
4.0 |
Inserts the item(s) to the beginning of the Array. |
| valueOf |
3.0 |
3.0 |
Like toString, returns the Array as a string. |
* Prototype functions are available to make this method available to
Internet Explorer and older browsers.
Array.concat(value1[value2[value...]])
The concat method appends the passed values to the end of the Array,
passing back a NEW array containing the joined values.
The values passed to the concat method can be anything you can assign
to a variable in Javascript.
var myArray = [1,2,3];
var newArray= [4,5,6];
var seven = 7;
var eight = 'eight';
var nine = {'sky':'blue', 'grass':'green'};
var joinedArray=myArray.concat(newArray, seven, eight, nine);
document.writeln(myArray); // outputs: 1,2,3
document.writeln(joinedArray); // outputs: 1,2,3,4,5,6,7,'eight',[object Object]
Supported Since: Netscape 4.0, IE 4.0
Array.every(function)
The every method is a Firefox method which accepts a function as an
argument. Every value of the array is passed to that
function until the function returns false. If no elements return false
then every will return true, if an element returned false
then every will return false. It's a convenient way to test an Array
and see if every element is a number for instance.
This method will pass the current value, the current index, and a
pointer to the array to your function. myfunction(curValue, curIndex,
curArray)
var isNumeric = function(x) {
// returns true if x is numeric and false if it is not.
var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
return String(x).match(RegExp);
}
var myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
document.writeln(myArray.every(isNumeric)); // outputs: true
var myArray = [1,2,3,4,5,6,7,8,9,'ten',11,12,13,14,15];
document.writeln(myArray.every(isNumeric)); // outputs: false
This method can be
prototyped to allow Internet Explorer and older browsers to use
this method. Simply copy the following code into
your Javascript toolbox and the .every() method will be available
regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.every)
{
Array.prototype.every = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
!fun.call(thisp, this[i], i, this))
return false;
}
return true;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.filter(function)
Filter creates a new Array of items which evaluate to true in the
supplied function. In the Array.every() method, we tested if the entire
Array was composed of Numbers. In Array.filter() we can extract all the
numbers, creating a new Array in the process.
This method will pass the current value, the current index, and a
pointer to the array to your function. myfunction(curValue, curIndex,
curArray)
Here we pass the array through the same function as .every() --
isNumeric -- and if the element is a number it's placed in the new
oddArray
Array.
var isNumeric = function(x) {
// returns true if x is numeric and false if it is not.
var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
return String(x).match(RegExp);
}
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,'ten'];
var oddArray=myArray.filter(isNumeric);
document.writeln(oddArray); // outputs: 1,3,5,7,9
This method can be
prototyped to allow Internet Explorer and older browsers to use
this method. Simply copy the following code into your
Javascript toolbox and the .filter() method will be available
regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
{
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.forEach(function)
This is an odd little method. All it does is pass each element of the
Array to the passed function. It ignores any results from the function
and it returns nothing itself. It will pass all the Array contents
through the function of your choice but the Array itself will not be
affected
and it will return nothing by itself.
This method will pass the current value, the current index, and a
pointer to the array to your function. myfunction(curValue, curIndex,
curArray)
var printArray = function (x, idx) {
document.writeln('['+idx+'] = '+x);
}
var myArray = [1,'two',3,'four',5];
myArray.forEach(printArray); // outputs: [0] = 1 [1] = two [2] = 3 [3] = four [4] = 5
This method can be
prototyped to allow Internet Explorer and older browsers to use
this method. Simply copy the following code into your
Javascript toolbox and the .forEach() method will be available
regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.join(delimeter)
The join method will output your Array as a string with a delimiter of
your choice. This is a very useful function if you need to convert
an Array into something you can send back to the server. Simply pick a
unique delimiter which is not likely to appear inside the data in your
Array then you can turn it back into an Array on the server side.
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,'ten'];
var test1 = myArray.join();
var test2 = myArray.join(', ');
var test3 = myArray.join('+');
document.writeln(test1+'<BR>'); // outputs: 1,two,3,four,5,six,7,eight,9,ten
document.writeln(test2+'<BR>'); // outputs: 1, two, 3, four, 5, six, 7, eight, 9, ten
document.writeln(test3+'<BR>'); // outputs: 1+two+3+four+5+six+7+eight+9+ten
Supported Since: Netscape 3.0, Internet Explorer: 3.0
Array.indexOf(searchStr[, startIndex])
The indexOf method will search the array until it matches your search
critera. It will then return the index where the item was found.
It will match only one item and the match must be exact. This is not
as useful as the custom .find() method provided below in the
Useful Prototypes
section.
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,'ten'];
document.writeln(myArray.indexOf('six')); // outputs: 5
document.writeln(myArray.indexOf('not here')); // outputs: -1
To find and return all occurrences of an item you can use the following
code…
var foundItems = [];
var index = array.indexOf(element)
while (index != -1)
{
foundItems.push(index);
index = array.indexOf(element, ++index);
}
This will create an array of indexes which match your search criteria
(element) and store them in foundItems[].
This method can be
prototyped to allow Internet Explorer and older browsers to use
this method. Simply copy the following code into
your Javascript toolbox and the .indexOf() method will be available
regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.lastIndexOf(searchStr[, startIndex])
Array.indexOf() searches from first to last, lastIndexOf searches from
last to first.
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,5,'ten'];
document.writeln(myArray.lastIndexOf(5)); // outputs: 9
document.writeln(myArray.lastIndexOf('not here')); // outputs: -1
This method can be
prototyped to allow Internet Explorer and older browsers to use
this method. Simply copy the following code into your
Javascript toolbox and the .lastIndexOf() method will be available
regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.lastIndexOf)
{
Array.prototype.lastIndexOf = function(elt /*, from*/)
{
var len = this.length;
var from = Number(arguments[1]);
if (isNaN(from))
{
from = len - 1;
}
else
{
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
else if (from >= len)
from = len - 1;
}
for (; from > -1; from--)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.map(function)
The map method will call the provided function for each value of the
array and it will return an array containing the results of those function
calls.
The callback function is called with three arguments: the value, the
index, and a pointer to the array being used respectively.
In the following example each element of the array is tested to see if
it is numeric, if it is, it's passed into the new array, otherwise a zero
is inserted.
var isNumeric = function(x) {
// returns true if x is numeric and false if it is not.
var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
return String(x).match(RegExp);
}
var testElement = function(x) {
if (isNumeric(x)) {
return x;
} else {
return 0;
}
}
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,'ten'];
var newArray= myArray.map(testElement);
document.writeln(newArray); // outputs: 1,0,3,0,5,0,7,0,9,0
This method can be
prototyped to allow Internet Explorer and older browsers to use
this method. Simply copy the following code into
your Javascript toolbox and the .map() method will be available
regardless of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.pop()
The pop() method implements a basic
stack structure in Javascript Arrays. Array.pop() will return the last
element of an Array and
delete it from the Array.
var myArray = [1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray+'<BR>'); // outputs: 1,2,3,4,5,6,7,8,9,10
document.writeln(myArray.length+'<BR>'); // outputs: 10
var popped = myArray.pop();
document.writeln(popped+'<BR>'); // outputs: 10
document.writeln(myArray+'<BR>'); // outputs: 1,2,3,4,5,6,7,8,9
document.writeln(myArray.length+'<BR>'); // outputs: 9
Supported Since: Netscape 4.0, Internet Explorer: 5.5
Array.push(value[,value2[, value...]])
The push() method adds the passed value(s) to the end of the array. In
addition to being incredibly useful for adding items to the array,
it also allows the Array to emulate a basic
stack structure.
var myArray = [1,2,3,4,5];
document.writeln(myArray+'<BR>'); // outputs: 1,2,3,4,5
document.writeln(myArray.length+'<BR>'); // outputs: 5
myArray.push(6);
document.writeln(myArray+'<BR>'); // outputs: 1,2,3,4,5,6
document.writeln(myArray.length+'<BR>'); // outputs: 6
myArray.push(7,8,9,10);
document.writeln(myArray+'<BR>'); // outputs: 1,2,3,4,5,6,7,8,9,10
document.writeln(myArray.length+'<BR>'); // outputs: 10
Supported Since: Netscape 4.0, Internet Explorer: 5.5
Array.reverse()
The reverse() method takes the array and reverses the order so the
first item becomes the last and the last item becomes the first.
var myArray = [1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray+'<BR>'); // outputs: 1,2,3,4,5,6,7,8,9,10
myArray.reverse();
document.writeln(myArray+'<BR>'); // outputs: 10,9,8,7,6,5,4,3,2,1
Supported Since: Netscape 3.0, Internet Explorer: 3.0
Array.shift()
The shift() method returns the first item in the Array, removing it
from the Array in the process. Together with
Array.unshift, Shift implements
a basic
queue structure in Javascript Arrays.
var myArray = [1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray+'<BR>'); // outputs: 1,2,3,4,5,6,7,8,9,10
theItem = myArray.shift();
document.writeln(theItem+'<BR>'); // outputs: 1
document.writeln(myArray+'<BR>'); // outputs: 2,3,4,5,6,7,8,9,10
Supported Since: Netscape 5.5, Internet Explorer: 4.0
Array.slice([begin[, end]])
The slice() method copies a block of the array and returns it to your
new variable. If you don't specify a beginning index the slice will begin
at
zero. If you don't specify and ending index the splice will continue
to the end of the Array. So to make a copy of the array simply don't pass
any arguments to the method.
var myArray = [1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray+'<BR>'); // outputs: 1,2,3,4,5,6,7,8,9,10
var newArray = myArray.slice();
document.writeln(newArray+'<BR>'); // outputs: 1,2,3,4,5,6,7,8,9,10
var newArray = myArray.slice(5);
document.writeln(newArray+'<BR>'); // outputs: 6,7,8,9,10
var newArray = myArray.slice(5,7);
document.writeln(newArray+'<BR>'); // outputs: 6,7
Supported Since: Netscape 4.0, Internet Explorer: 4.0
Array.some(function)
The some() method will pass each element of the Array through the
supplied function until true has been returned. If the function returns
true some will in turn return true. If the entire array has been
traversed and no true condition was found then some() will return false.
var isNumeric = function(x) {
// returns true if x is numeric and false if it is not.
var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
return String(x).match(RegExp);
}
var myArray = ['one', 'two', 'three', 'four', 'five'];
document.writeln(myArray.some(isNumeric)); // outputs: false
var myArray = ['one', 'two', 3, 'four', 'five'];
document.writeln(myArray.some(isNumeric)); // outputs: true
This method can be
prototyped to allow Internet Explorer and older browsers to use
this method. Simply copy the following code into your
Javascript toolbox and the .some() method will be available regardless
of your browser version.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.some)
{
Array.prototype.some = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
fun.call(thisp, this[i], i, this))
return true;
}
return false;
};
}
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.sort([function])
The sort() method, by default, will sort an Array alphabetically. If
you would like to create your own sorting criteria, supply a function
for the sort method to call. Sort will pass your function (a,b). If a
is less than b then return -1, if a is equal to b then return 0, if a is
greater than b then return 1. Sort will take it from there.
var myArray=[8,10,50,5,7,83,24,19,168];
myArray.sort()
document.writeln(myArray); // 10,168,19,24,5,50,7,8,83 (sorted alphabetically)
myArray.sort( function (a,b) { return a-b }); // Sort Numerically
document.writeln(myArray); //5,7,8,10,19,24,50,83,168
function compare(a, b) {
// psudeo code.
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
if (a == b) {
return 0;
}
}
myArray.sort(compare);
Supported Since: Netscape 3.0, Internet Explorer: 3.0
Array.splice(start[, howmany[, element1[,element...]]])
The splice() method at it's most basic allows you to delete an element
from the array by simply specifying the index you'd like to
delete and then how many elements you'd like to delete from that point.
You can also specify any number of elements to insert into
the array at that point.
splice() returns a new array containing the removed items. If you
specify a starting number but don't specify how many,
splice will truncate the array.
You can insert elements into the array without deleting anything by
specifying zero for howmany.
var myArray=[1,2,3,4,5,6,7,8,9,10];
var newArray=[];
//delete one item at the 5th index.
newArray = myArray.splice(5,1);
document.writeln(myArray); // outputs: 1,2,3,4,5,7,8,9,10
document.writeln(newArray); // outputs 6
//truncate the array at the 5th index.
myArray=[1,2,3,4,5,6,7,8,9,10];
newArray = myArray.splice(5);
document.writeln(myArray); // outputs: 1,2,3,4,5
document.writeln(newArray); // outputs 6,7,8,9,10
// do nothing at all.
myArray=[1,2,3,4,5,6,7,8,9,10];
newArray = myArray.splice();
document.writeln(myArray); // outputs: 1,2,3,4,5,6,7,8,9,10
document.writeln(newArray); // outputs undefined
// cut out the middle and insert 'blue', and 'green'
myArray=[1,2,3,4,5,6,7,8,9,10];
newArray = myArray.splice(1,8, 'blue', 'green');
document.writeln(myArray); // outputs: 1,blue,green,10
document.writeln(newArray); // outputs 2,3,4,5,6,7,8,9
// Insert without deleting.
myArray=[1,2,3,4,5,6,7,8,9,10];
newArray = myArray.splice(5,0, '*');
newArray = myArray.splice(4,0, '*');
document.writeln(myArray); // outputs: 1,2,3,4,*,5,*,6,7,8,9,10
Supported Since: Netscape 4.0, Internet Explorer: 5.5
Array.toSource()
The toSource() method is a Firefox only extension which takes the
contents of an Array and returns the source code
.
That is, if you were to use the toSource() method and pass it through
an eval statement you could rebuild the array.
This is a useful debugging method and can be useful in Ajax/JSON
applications. There is no prototype for this method, it works only in
Firefox.
var myArray = ["a", "b", "c", {'sky':'blue', 'grass':'green'}];
var theSource = myArray.toSource()
document.writeln(theSource); // outputs: ["a", "b", "c", {sky:"blue", grass:"green"}]
Supported Since: Firefox 1.5, Internet Explorer: ---
Array.toString()
This method outputs the contents of the Array as a string. It's not as
powerful as toSource() since it doesn't expand objects
but it is supported by browsers other than firefox.
var myArray = ["a", "b", "c", {'sky':'blue', 'grass':'green'}];
var theSource = myArray.toString()
document.writeln(theSource); // outputs: a,b,c,[object Object]
Supported Since: Netscape 3.0, Internet Explorer: 3.0
Array.unshift(value1[, value2[, value...]])
The unshift method inserts the value(s) passed in the method's
arguments into the start of the Array. Together with the shift(),
unshift() implements a basic
queue structure in Javascript Arrays.
var myArray = [1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray+'<BR>'); // outputs: 1,2,3,4,5,6,7,8,9,10
myArray.unshift('a','b','c');
document.writeln(myArray+'<BR>'); // outputs: a,b,c,1,2,3,4,5,6,7,8,9,10
Supported Since: Netscape 5.5, Internet Explorer: 4.0
Array.valueOf()
See
Array.toString().
Howto Delete An Element From An Array
You can delete an item from an Array with the splice() method. Simply
supply the index of the item you wish to delete and
how many items you want to delete and the item(s) will be removed for
you.
var myArray=[1,2,3,4,5,6,7,8,9,10];
myArray.splice(5,1); //delete one item at the 5th index.
document.writeln(myArray); // outputs: 1,2,3,4,5,7,8,9,10
Howto Easily Add Items To An Array
There are three ways to easily add items to an array. First you can use
the Array.length property. Since Arrays start with index 0,
then Array.length is always equal to the first empty index at the end
of the Array.
var myArray = [];
myArray[0] = 'January';
myArray[1] = 'February';
document.writeln(myArray.length); // Will output: 2
myArray[myArray.length] = 'March'; // Adds Item to end of Array
document.writeln(myArray.length); // Will output: 3
document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2>March
You can add the .push() method of the Array. This will add the
requested items to the end of the Array.
var myArray = [];
myArray[0] = 'January';
myArray[1] = 'February';
myArray.push('March'); // Adds Item to end of Array
document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2>March
You can use the .unshift() method to insert an item at the BEGINNING of
the array!
var myArray = [];
myArray[0] = 'February';
myArray[1] = 'March';
myArray.unshift('January'); // Adds Item to beginning of Array
document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>January
document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>February
document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2>March
Howto Clear-out/Reset An Array
Clearing out or resetting an array is as simple as assigning it a new
empty bracket.
var myArray=[1,2,3,4,5,6,7,8,9,10];
document.writeln(myArray); // outputs: 1,2,3,4,5,6,7,8,9,10
myArray = []; // clear-out the array
document.writeln(myArray); // outputs null
Alternatively you can set the length of the array to zero (myArray.length=0),
likewise if you just need to clear out a few items
at the end of the array, lower the length property by the number of
items you would like removed from the end of the array.
Howto Tell The Difference Between An Array And An Object
Because Javascript's Array is just a modified Javascript object, it's
actually not that easy to differentiate an Array and an Object,
even when you absolutely need to. So here's a little function that
will let you ask the array itself what it is. isArray() will return
true if it's an array and false if it is not an Array.
function isArray(testObject) {
return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object'
&& typeof testObject.length === 'number';
}
Usage:
var tmp = [5,9,12,18,'blue',30,7,97,53,33,30,35,27,30];
var tmp2 = {0:5,1:9,2:12}
test1 = isArray(tmp); // returns true
test2 = isArray(tmp2); // returns false;
Howto Pass An Array Via Ajax
If you have an Array you need to package up and send via Ajax, you need
to use the join
method to turn your Array into a string.
Find a unique character that is unlikely to appear inside your Array
and use it as your delimiter. For most applications the tildie (~)
character is a safe delimeter to use.
var myArray=[1,2,3,4,5,6,7,8,9,10];
var theData = myArray.join('~'); // theData=1~2~3~4~5~6~7~8~9~10
theData=encodeURIComponent(theData); // Optional but safe! Escape the data
Now just send theData
through your ajax routine. On the server
just do a
split('~') in php to turn it back into an Array.
Howto Receive An Array Via Ajax
On the server side convert the Array into a string using a unique
delimiter --
implode in php. (We're assuming a string with a tildie [~]
delimiter in this example).
Once you've received the string from your Ajax handler simply use the
string's split
method to bust the string into an Array.
var ajaxStr = '1~2~3~4~5~6~7~8~9~10';
var myArray = ajaxStr.split('~');
document.writeln(myArray); // outputs: 1,2,3,4,5,6,7,8,9,10
Useful Prototypes
With prototypes you can extend the Array object and include any
additional functionality you wish. For instance, the Array.sort()
method sorts alphabetically by default but adding a numerical sort is
as simple as including the following snippet of code in your toolbox.
Array.prototype.sortNum = function() {
return this.sort( function (a,b) { return a-b; } );
}
All this does is make sortNum a method of Array just like sort and
splice and join and all the other default methods. Any array can
access it, even arrays that haven't been assigned to variables…
document.writeln([5,8,12,50,25,80,93].sortNum()); // outputs 5,8,12,25,50,80,93
Since the Javascript Array object is already so rich, there's not much
left that needs to be done. However, there are a few snippets
people have found helpful.
Useful Prototypes: Array.sortNum()
As stated above, just use the sortNum() method when you want to sort an
array numerically instead of alphabetically.
Array.prototype.sortNum = function() {
return this.sort( function (a,b) { return a-b; } );
}
Useful Prototypes: Array.find(searchStr)
Array.indexOf() is a nice method but this extension is a little more
powerful and flexible. First it will return an array of all the indexes
it found (it will return false if it doesn't find anything). Second in
addition to passing the usual string or number to look for you can
actually pass a regular expression, which makes this the ultimate Array
prototype in my book.
Array.prototype.find = function(searchStr) {
var returnArray = false;
for (i=0; i<this.length; i++) {
if (typeof(searchStr) == 'function') {
if (searchStr.test(this[i])) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
} else {
if (this[i]===searchStr) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
}
}
return returnArray;
}
Usage¦
var tmp = [5,9,12,18,56,1,10,42,'blue',30, 7,97,53,33,30,35,27,30,'35','Ball', 'bubble'];
// 0/1/2 /3 /4/5 /6 /7 /8 /9/10/11/12/13/14/15/16/17/ 18/ 19/ 20
var thirty=tmp.find(30); // Returns 9, 14, 17
var thirtyfive=tmp.find('35'); // Returns 18
var thirtyfive=tmp.find(35); // Returns 15
var haveBlue=tmp.find('blue'); // Returns 8
var notFound=tmp.find('not there!'); // Returns false
var regexp1=tmp.find(/^b/); // returns 8,20 (first letter starts with b)
var regexp1=tmp.find(/^b/i); // returns 8,19,20 (same as above but ignore case)
Useful Prototypes: Array.shuffle()
The anti-sort, this shuffle() method will take the contents of the
array and randomize them. This method is surprisingly useful and
not just for shuffling an array of virtual cards.
Array.prototype.shuffle = function (){
for(var rnd, tmp, i=this.length; i; rnd=parseInt(Math.random()*i), tmp=this[--i], this[i]=this[rnd],
this[rnd]=tmp);
};
Usage:
var myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
myArray.shuffle();
document.writeln(myArray); // outputs~: 8,1,13,11,2,3,4,12,6,14,5,7,10,15,9
Useful Prototypes: Array.compare(array)
If you need to be able to compare Arrays this is the prototype to do
it. Pass an Array you want to compare and if they are identical the
method will return true. If there's a difference it will return false.
The match must be identical so '80' is not the same as 80.
Array.prototype.compare = function(testArr) {
if (this.length != testArr.length) return false;
for (var i = 0; i < testArr.length; i++) {
if (this[i].compare) {
if (!this[i].compare(testArr[i])) return false;
}
if (this[i] !== testArr[i]) return false;
}
return true;
}
Usage:
var myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var yourArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
document.writeln(myArray.compare(yourArray)); // outputs: true;
yourArray[0]='1';
document.writeln(myArray.compare(yourArray)); // outputs: false;
yourArray[0]='one';
document.writeln(myArray.compare(yourArray)); // outputs: false;
yourArray[0]=1;
document.writeln(myArray.compare(yourArray)); // outputs: true;