Number
is the built-in object corresponding to the primitive number data type. As discussed in Chapter 3, all
var x = new Number(); var y = new Number(17.5);
Table 7-5 lists the special numeric values that are provided as properties of the Number object.
|
Property |
Value |
|---|---|
|
Number.MAX_VALUE |
Largest magnitude representable |
|
Number.MIN_VALUE |
Smallest magnitude representable |
|
Number.POSITIVE_INFINITY |
The special value Infinity |
|
Number.NEGATIVE_INFINITY |
The special value -Infinity |
|
Number.NaN |
The special value NaN |
The only useful method of this object is
toString()
, which returns the value of the number in a string. Of course it is rarely needed, given that
String
is the built-in object corresponding to the primitive string data type. It contains a very large number of
The String() constructor takes an optional argument that specifies its initial value:
var s = new String();
var headline = new String("Dewey Defeats Truman");
Because you can invoke String methods on primitive strings, programmers rarely create String objects in practice.
The only property of
String
is
length
, which indicates the number of
var s = "String fun in JavaScript"; var strlen = s.length; // strlen is set to 24
The
length
property is automatically updated when the string changes and cannot be set by the programmer. In fact there is
no
way to manipulate a string directly. That is,
String
methods do not
var s = "abc"; s = s.toUpperCase(); // s is now "ABC"
Invoking s.toUpperCase() without setting s equal to its result does not change the value of s . The following does not modify s :
var s = "abc"; s.toUpperCase(); // s is still "abc"
Other simple string manipulation methods such as
toLowerCase()
work in the same way;
Individual characters can be examined with the charAt() method. It accepts an integer indicating the position of the character to return. Because JavaScript makes no distinction between individual characters and strings, it returns a string containing the desired character. Remember that, like arrays, characters in JavaScript strings are enumerated beginning with zero; so
"JavaScript".charAt(1);
retrieves a. You can also retrieve the numeric value associated with a particular character using charCodeAt() . Because the value of a in Unicode is 97 , the following statement
"JavaScript".charCodeAt(1);
returns 97 .
Conversion from a character code is easy enough using the
fromCharCode()
method. Unlike the other methods, this is
var aChar = String.fromCharCode(82);
would set the value of the variable aChar to R . Multiple codes can be passed in by separating them with commas. For example,
var aString = String.fromCharCode(68,79,71);
would set aString to DOG.
| Note |
You will probably receive a
?
value or a
|
The indexOf() method takes a string argument and returns the index of the first occurrence of the argument in the string. For example,
"JavaScript".indexOf("Script");
returns 4 . If the argument is not found, “1 is returned. This method also accepts an optional second argument that specifies the index at which to start the search. When specified, the method returns the index of the first occurrence of the argument at or after the start index. For example,
"JavaScript".indexOf("a", 2);
returns
3
. A
"JavaScript".lastIndexOf("a", 2);
returns 1 . This method also returns “1 if the string is not found.
There are
"JavaScript".substring(3);
returns aScript, and
"JavaScript".substring(3, 7);
returns aScr. The slice() method is a slightly more powerful version of substring() . It accepts the same arguments as substring() but the indices are allowed to be negative. A negative index is treated as an offset from the end of the string.
The
match()
and
search()
methods use regular expressions to perform more complicated examination of strings. The use of regular expressions is discussed in the
The most basic operation one can perform with strings is concatenation. Concatenating strings with the + operator should be familiar by now. The String object also provides a concat() method to achieve the same result. It accepts any number of arguments and returns the string obtained by concatenating the arguments to the string on which it was invoked. For example,
var s = "JavaScript".concat(" is", " a", " flexible", " language.");
var s = "JavaScript" + " is" + " a" + " flexible" + " language";
A method that comes in very useful when parsing preformatted strings is
split()
. The
split()
method breaks the string up into separate strings according to a
var wordArray = "A simple example".split(" ");
assigns wordArray an array with three elements, A, simple, and example. Passing the empty string as the delimiter breaks the string up into an array of strings containing individual characters. The method also accepts a second argument that specifies the maximum number of elements into which the string can be broken.
Because JavaScript is commonly used to manipulate Web pages, the
String
object provides a large set of methods that mark strings up as HTML. Each of these methods returns the string
var s = "This is very important".bold();
places this string in s :
<< B >>This is very important<< /B >>
You may
var s = "This is important".bold().strike().blink();
assigns the following string to s :
<<BLINK>><<STRIKE>><<B>>This is important<</B>><</STRIKE>><</BLINK>>
This displays a blinking, struck-through, bold string when placed in a Web document. Ignoring the fact that such strings are incredibly annoying, the example illustrates how method invocations can be chained together for efficiency. It is easier to write the invocations in series than to invoke each on s , one at a time. Note how the methods were invoked inner-first, or, equivalently, left to right.
The various HTML
String
methods
|
Method |
Description |
Example |
|---|---|---|
|
anchor("
|
Creates a named anchor specified by the < A > element using the argument name as the value of the corresponding attribute. |
var x = "Marked point".anchor("marker");
|
|
big() |
Creates a < BIG > element using the provided string. |
var x = "Grow".big(); |
|
blink() |
Creates a blinking text element
|
var x = "Bad Netscape".blink(); |
|
bold() |
Creates a bold text element indicated by < B > out of the provided string. |
var x = "Behold!".bold(); |
|
fixed() |
Creates a fixed width text element indicated by <
TT
> out of the
|
var x = "Code".fixed(); |
|
fontcolor(
|
Creates a < FONT > tag with the color specified by the argument color. The value passed should be a valid hexadecimal string value or a string specifying a color name. |
var x = "green".font("green");
|
|
Fontsize(
|
Takes the argument specified by size that should be either in the range 1 “7 or a relative +/ “ value of 1 “7 and creates a < FONT > tag. |
var x = "Change size".font(7); |
|
italics() |
Creates an italics element <I>. |
var x = "Special".italics(); |
|
Link(location) |
Takes the argument location and forms a link with the < A > element using the string as the link text. |
var x = "click here".location("http://www.pint.com/");
|
|
small() |
Creates a < SMALL > element out of the provided string. |
var x = "Shrink".small(); |
|
strike() |
Creates a < STRIKE > element out of the provided string. |
var x = "Legal".strike(); |
|
Sub() |
Creates a subscript element specified
|
var x = "test".sub() |
|
Sup() |
Creates a superscript element specified
|
var x = "test".sup() |
| Note |
You may notice that it is possible to pass just about anything to these HTML methods. For example "bad".fontcolor('junk') will happily create a string containing the markup << FONT COLOR="junk" >> bad << /FONT >> . No range or type checking related to HTML is provided by these methods. |
Notice in Table 7-6 how these JavaScript methods produce uppercase and even nonstandard markup like <<
BLINK
>> rather than XHTML-compliant tags. In fact, many of the methods like
fontcolor()
create markup strings containing deprecated elements that have been phased out under strict variants of HTML 4 and XHTML in favor of CSS-based presentation. Yet given the unfortunately somewhat slow uptake of XHTML and the only-recent improving adoption of CSS on the Web at large, it is pretty