JavaScript Editor JavaScript Debugger     JavaScript Editor 



Team LiB
Previous Section Next Section

String

String is the built-in object corresponding to the primitive string data type. It contains a very large number of methods for string manipulation and examination, substring extraction, and even conversion of strings to marked-up HTML, though unfortunately not standards-oriented XHTML. A full description of all String methods, including examples, is included in Appendix B. Here we highlight most of them with special focus on those that are most commonly used.

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 characters in the string.

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 operate on their data “in place.” Any method that would change the value of the string, returns a string containing the result. If you want to change the value of the string, you must set the string equal to the result of the operation. For example, converting a string to uppercase with the toUpperCase() method would require the following syntax:

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; forgetting this fact is a common mistake made by new JavaScript programmers.

Examining Strings

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 generally used with the generic object String itself rather than a string instance. For example,

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 strange character for any unknown values passed to the fromCharCode() method.

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 related method is lastIndexOf(), which returns the index of the last occurrence of the string given as an argument. It also accepts an optional second argument that indicates the index at which to end the search. For example,

"JavaScript".lastIndexOf("a", 2);

returns 1. This method also returns –1 if the string is not found.

There are numerous ways to extract substrings in JavaScript. The best way to do so is with substring(). The first argument to substring() specifies the index at which the desired substring begins. The optional second argument indicates the index at which the desired substring ends. The method returns a string containing the substring beginning at the given index up to but not including the character at the index specified by the second argument. For example,

"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 next chapter.

Manipulating Strings

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.");

assigns “JavaScript is a flexible language.” to the variable s, just as the following would:

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 delimiter passed as its first argument. The result is returned in an array. For example,

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.

Marking Up Strings as Traditional HTML

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 surrounded by a pair of HTML tags. Note that the HTML returned is not standards-oriented HTML 4 or XHTML but more like the old physical style HTML 3.2. For example, the bold() method places <<B>> and <</B>> tags around the string it is invoked on; the following

var s = "This is very important".bold();

places this string in s:

<<B>>This is very important<</B>>

You may wonder how to apply more than one HTML-related method to a string. This is easily accomplished by chaining method invocations. While chained method invocations can appear intimidating, they come in handy when creating HTML markup from strings. For example,

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 correspond to common HTML 3.2 and browser-specific tags like <<BLINK>>. A complete list of the HTML-related String methods can be found in Table 7-6.

Table 7-6: HTML-Releated String Methods

Method

Description

Example

anchor("name")

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");
// <A NAME="marker">Marked point</A>

big()

Creates a <BIG> element using the provided string.

var x = "Grow".big();
// <BIG>Grow</BIG>

blink()

Creates a blinking text element enclosed by <BLINK> out of the provided string despite Internet Explorer's lack of support for the <BLINK> element.

var x = "Bad Netscape".blink();
// <BLINK>Bad Netscape</BLINK>

bold()

Creates a bold text element indicated by <B> out of the provided string.

var x = "Behold!".bold();
// <B>Behold!</B>

fixed()

Creates a fixed width text element indicated by <TT> out of the
provided string.

var x = "Code".fixed();
// <TT>Code</TT>

fontcolor(color)

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");
// <FONT COLOR="green">Green</FONT>
var x = "Red".font("#FF0000");
// <FONT COLOR="#FF0000">Red</FONT>

Fontsize(size)

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);
// <FONT SIZE="7">Change size</FONT>
var x = "Change size".font("+1");
// <FONT SIZE="+1">Change size</FONT>

italics()

Creates an italics element <I>.

var x = "Special".italics();
// <I>Special</I>

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/");
// <A HERF="http://www.pint.com">
// click here</A>

small()

Creates a <SMALL> element out of the provided string.

var x = "Shrink".small();
// <SMALL>Shrink</SMALL>

strike()

Creates a <STRIKE> element out of the provided string.

var x = "Legal".strike();
// <STRIKE>Legal</STRIKE>

Sub()

Creates a subscript element specified
by <SUB> out of the provided string.

var x = "test".sub()
// <SUB>test</SUB>

Sup()

Creates a superscript element specified
by <SUP> out of the provided string.

var x = "test".sup()
// <SUP>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 unlikely that the transition away from these elements will happen soon. Fortunately, once this does happen, we are going to have a much better set of HTML-related JavaScript methods than these String methods. The Document Object Model will allow us to easily create and manipulate any HTML element, as discussed starting in Chapter 10. Before concluding this chapter, it is important to understand one subtle issue concerning type-related objects.


Team LiB
Previous Section Next Section


JavaScript Editor JavaScript Debugger     JavaScript Editor


©