JavaScript Reference
Examples:
var employeeOfTheMonth = {
name: "Bob",
title: "Vice-president",
age: 45,
"home address": {street: "Abbey Road", country: "UK"}
};
var point = {x: -3.6, y: 2}; //An object with properties x and y
var o = {}; //An empty object
Properties
prototype
Syntax:
object .prototype
The prototyp e property is used as part of the JavaScript inheritance mech anism.
You will use this property to add properties and methods to Function objects that act
as co nstructors for a class of objects.
Say, for example, that you wish to augment the Date JavaScript class with a method
that returns true if the specified year is a leap year, and false if it is not a leap year.
In the Gregorian calendar, a year is a le ap year if it is evenly divisible by four but not
with 100. However, if the year is evenly divisible by 4 00, it is again a leap year. Here
is how you can do it:
//Add isLeapYear() to the Date’s prototype property:
Date.prototype.isLeapYear = function() {
var y = this.getFullYear();
return ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0);
};
var d = new Date();
//d inherits the isLeapYear() method:
if (d.isLeapYear()) {
console.log(d.getFullYear() + " is a leap year.");
}
else {
console.log(d.getFullYear() + " is not a leap year.");
}
E.16 String (Core JavaScript)
String is a JavaScript’s primitive data type and the String class type provides methods
for working with primitive string values. For example, you can search a string to
E.16. String (Core JavaScript) 421
find a character or substring in it, or you can convert all string c haracters to upper
case. Keep in mind that strings in JavaScript are immutable, which means that you
cannot mo dify the contents of a string. As a consequence, String methods such as
toUpperCase() d on’t m odify the or iginal string, but in stead return a completely new
one. Beca use strings act like read-only arrays of single -character strings, you can use
the [ ] ope rator to extract a character from a strin g.
Object Instance Creation
String() //Constructor
Syntax:
new String(val ) //Constructor
String(val ) //Conversion function
String() can be used either as a co nstructor (w ith the new operator) or conversion
function (without the new operator). Either way, S tring() first converts val to
string. The String() constructor then creates an d returns a String object holding
the string representation of val , while the String() conversion func tion simply re-
turns the converted value as a primitive string.
When you use any of the String properties or methods on a prim itive string value,
JavaScript a utomatically crea te s a temp orary wrap per String object in order to be able
to use the property or invoke the method.
Properties
length
Syntax:
string .length
This read-o nly property is an integer that specifies the number of characters in a string.
The index of the last character is length - 1.
Examples:
var s = "abc";
s[s.length - 1] //Returns "c"
"Count my characters".length //Returns 19
422 JavaScript Reference
JavaScript Reference
Methods
charAt()
Syntax:
string .charAt(n )
This method returns the nth character of string . Note that the first character of
a string has the index of zero and the last character has the index length - 1. If
n does not specify a valid character index, then charAt() returns an empty string.
Because JavaScript does not define a spe cial characte r data type, the returned character
is a string of length 1.
Strings act like read -only arrays of single-cha racter strings, which means tha t instead
of charAt(), you can also use the [ ] operator to extract a character from a string.
Examples:
var s = "Something blue";
s.charAt(2) //Returns "m"
s[2] //Same as s.charAt(2)
charCodeAt()
Syntax:
string .charCodeAt(n )
This method is like charAt(), o nly it returns the Unicode character encoding of the
character at a given location, instead of the string containing the character proper. If
n does not specify a valid character index (i.e., is negative or greate r than length -
1), then charCodeAt() return s NaN.
Examples:
var s = "abc";
s.charCodeAt(2) //Returns 99
s.charCodeAt(3) //Returns NaN
"W".charCodeAt(0) //Returns 87
fromCharCode() //Static method
Syntax:
String.fromCharCode(char1 , char2 , ..., charN )
E.16. String (Core JavaScript) 423
This meth od cre ates a string from one or mo re individual characters, spec ified by their
numeric Unicode encodings (char1 to charN ).
Example:
//Creates the string "What’s up?":
var greeting = String.fromCharCode(87, 104, 97, 116, 39, 115, 32,
117, 112, 63);
indexOf()
Syntax:
string .indexOf(str )
string .indexOf(str , begin )
This method sear ches string for the first occurren ce o f str . The search starts a t the
beginning of string or, optionally, at position begin within string . The method
returns the index of the first c haracter of the first occurrence of str in string . If
str is not found, then -1 is retur ned. The search is ca se sensitive, but you can make it
case insensitive by using toUpperCase() or toLowerCase(). Because these meth-
ods return a modified copy of the string, you can chain them in a single expre ssion
with index Of(). Don’t forget tha t the position of the first character of the string is
numbered 0.
Examples:
var magic = "Abracadabra";
magic.indexOf("abra") //Returns 7
magic.toLowerCase().indexOf("abra") //Returns 0
magic.indexOf("abra", 8) //Returns -1
lastIndexOf()
Syntax:
string .lastIndexOf(str )
string .lastIndexOf(str , begin )
This method works like indexOf(), except that it searches string in the opposite di-
rection so that the first occurrenc e of str found is in fact the last one within string .
Note that, in spite of the reversed search direction, character positions are still num-
bered from the beginning. The first character within a string has the po sition 0, while
the last one has the po sition length - 1.
424 JavaScript Reference
JavaScript Reference
Examples:
var magic = "Abracadabra";
magic.lastIndexOf("abra", 8) //Returns 7
magic.lastIndexOf("abra", 6) //Returns -1
magic.toLowerCase().lastIndexOf("abra", 6) //Returns 0
magic.lastIndexOf("abra") //Returns 7
slice()
Syntax:
string .slice(begin )
string .slice(begin , end )
This method returns a portion (substring ) of string containing all characte rs from
and including the character at the p osition begin and up to but not including the
character at the position end . The meth od does not change string . The arguments
begin and end can also assume negative values, in which case they specify positions
counted from the end of the string . For example, -1 indicates the last cha racter, -2
the second to last character, and so forth. I f the end argument is omitted, then all
characters from begin to the end of the string are returned.
It is impo rtant to remember that the character at the position begin is included in
the returned substring while the ch aracter at the position end is not. This may seem
strange, but there are some noteworthy implications of this rule. Fir st, the len gth of
the returned string is always end - begin . Second, if you want to make several
contiguous slices of string , which you don’t want to overlap, you simply use the
end argum ent of the preced ing slice as the begin argum ent of the current slice.
Examples:
var s = "ABCDE";
s.slice(1) //Returns "BCDE"
s.slice(-1) //Returns "E" (the last character)
s.slice(0, 1) //Returns "A"
s.slice(1, -2) //Returns "BC"
split()
Syntax:
string .split()
string .split(delimiter )
This method creates and retur ns an array o f strings obtained by splittin g string into
substrings. The split() method first searches for all the occurrences of delimiter
E.16. String (Core JavaScript) 425
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.132.142