Section 5.6. String Operators


5.6. String Operators

As discussed in the previous sections, several operators have special effects when their operands are strings.

The + operator concatenates two string operandsthat is, it creates a new string that consists of the first string followed by the second. For example, the following expression evaluates to the string "hello there":

 "hello" + " " + "there" 

And the following lines produce the string "22":

 a = "2"; b = "2"; c = a + b; 

The <, <=, >, and >= operators compare two strings to determine their order. The comparison uses alphabetical order. As noted in Section 5.5.1, however, this alphabetical order is based on the Unicode character encoding used by JavaScript. In this encoding, all capital letters in the Latin alphabet come before (are less than) all lowercase letters, which can cause unexpected results.

The == and != operators work on strings, but, as you've seen, these operators work for all datatypes, and they do not have any special behavior when used with strings.

The + operator is a special one: it gives priority to string operands over numeric operands. As noted earlier, if either operand to + is a string (or an object), the other operand is converted to a string (or both operands are converted to strings) and concatenated, rather than added. On the other hand, the comparison operators perform string comparison only if both operands are strings. If only one operand is a string, JavaScript attempts to convert it to a number. The following lines illustrate:

 1 + 2        // Addition. Result is 3. "1" + "2"    // Concatenation. Result is "12". "1" + 2      // Concatenation; 2 is converted to "2". Result is "12". 11 < 3       // Numeric comparison. Result is false. "11" < "3"   // String comparison. Result is true. "11" < 3     // Numeric comparison; "11" converted to 11. Result is false. "one" < 3    // Numeric comparison; "one" converted to NaN. Result is false. 

Finally, it is important to note that when the + operator is used with strings and numbers, it may not be associative. That is, the result may depend on the order in which operations are performed. This can be seen with examples like these:

 s = 1 + 2 + " blind mice";   // Yields "3 blind mice" t = "blind mice: " + 1 + 2;  // Yields "blind mice: 12" 

The reason for this surprising difference in behavior is that the + operator works from left to right, unless parentheses change this order. Thus, the last two examples are equivalent to these:

 s = (1 + 2) + "blind mice";    // 1st + yields number; 2nd yields string t = ("blind mice: " + 1) + 2;  // Both operations yield strings 




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net