Visit Mozilla.org

Sandbox:JS:String

From MDC


String in JavaScript may refer to a string primitive, a string object, or the String function/constructor.

Contents

[edit] String primitives

A string primitive, a.k.a. string value, is a sequence of characters. Like any other primitive, strings are immutable; they cannot be changed after they are created.

String primitives are created by string literals. They are enclosed with either single quotes or double quotes.

[edit] Syntax

'characters'
"characters"
characters
A sequence of possibly escaped characters.

[edit] Escaped characters

Some characters are not allowed or cannot be represented in string literals, such as the newline character. These characters can be represented with escape sequences, which are composed of the character "\" preceding a code:

Name Escape Sequence Unicode Hex Value
unicode escape sequence \uHHHH HHHH (4-digit hex number)
hex escape sequence \xHH HH (2-digit hex number)
backspace \b 08
horizontal tab \t 09
line feed (new line) \n 0A
vertical tab \v 0B
form feed \f 0C
carriage return \r 0D
double quote \" 22
single quote \' 27
backslash \\ 5C

If the string literal is delimited by single quotes, double quotes within the literal do not need to be escaped. The reverse also applies: single quotes within a double quoted literal do not need to be escaped.

Escaping any other character besides the ones mentioned above (preceding the character with "\") results in that character. For example, the literals '\p' and 'p' are equivalent, both resulting in the value "p". To explicitly keep the backslash character, escape that backslash: the literal '\\p' results in the value "\p".

Extension to ECMAScript: String literals can be spread accross multiple lines by escaping the newline character, i.e. adding a "\" at the very end of the line (this is not the same as escaping "n" to produce the newline character). Such an escape sequence is evaluated as if the "\" and the newline never existed:

var str1 = 'Java\
Script';
var str2 = 'JavaScript';
// str1 is equivalent to str2

Although this is an extension, most JavaScript engines (including JScript) support this feature.

[edit] typeof

Applying the typeof operator on a string primitive returns the string "string".

[edit] String function

The String function converts its argument to a string primitive.

Primitives are implicitly converted into other types of primitives as needed, so it is rarely needed to explicitly use this funcion.

Note: The String function and String constructor are the same object. Precisely, String can be used in either a function call context or a construct call context.

[edit] Syntax

ret = String([value])
value
Any value. If omitted, defaults to the empty string.
ret
A new string primitive.

[edit] Type conversion operation

All convert-to-string operations, including implicit conversions, are performed by an internal function.

Input Result
undefined "undefined"
null "null"
true "true"
false "false"
NaN "NaN"
+0 or -0 "0"
Infinity "Infinity"
-Infinity "-Infinity"
number primitive, whose absolute value is between 10-6 and 1021 string composed of the following sequence:
  1. if negative, "-"
  2. digits whose positions are greater than or equal to the ones digit, or "0" if there are no such digits
  3. if there are more digits, "." and the rest of the digits

e.g. "-60.57", "0.00314", "1000"

any other number primitive string composed of the following sequence:
  1. if negative, "-"
  2. most significant digit
  3. if there are more digits, "." and the rest of the digits
  4. "e"
  5. "+" or "-", depending on the sign of the mathematical log of the number
  6. the mathematical base 10 log of the number

e.g. "1.23e+22", "-4.3985e-12"

string primitive returns the input (no conversion)
object returns object.toString(), converting the return value to a string primitive if necessary according to the rules specified by this table

Note: Replacing the String function does not replace this internal function, i.e. doing so has no effect on implicit conversions.

[edit] String constructor and string objects

A string object is a wrapper around string primitives and provides string-related methods and properties. It can be directly created with the String constructor.

The term string object can refer to either an object created by the String constructor or the String constructor itself. To differentiate between the two, sometimes the String constructor is referred to as the String object (with the S capitalized), while the term String instance can be used to describe the object "instantiated" by the String constructor.

The term string typically refers to a string primitive rather than a string object.

A string object is immutable in the sense that the string primitive it contains cannot be changed. However, like any other object, the properties of a string object can be changed.

[edit] Syntax

ret = new String([value])
value
A string primitive. If value is not a string primitive, it is converted to one. If omitted, defaults to the empty string.
ret
A new string object.

[edit] Relationship with string primitives

In practice, the difference between string primitives and string objects is mostly negligible, since string primitives and string objects implicitly and temporarily convert to one another. When you call any method or get any property on a string primitive, JavaScript engine implicitly "boxes" the string primitive within a temporary string object, calls the method, then discards this temporary object. Likewise, the string primitive within a string object is implicitly retrieved whenever necessary.

You should use string primitives, unless you explicitly need to use a string object, because string objects can have counterintuitive behavior. For example:

var s1 = "2 + 2";             // creates a string primitive
var s2 = new String("2 + 2"); // creates a string object
eval(s1);                     // returns 4
eval(s2);                     // returns s2 (does nothing)

Note: Replacing the String constructor has no effect on implicit conversions from string primitives to string objects.

[edit] Accessing individual characters in a string

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a 1 less than the string's length.

There are two ways to access an individual character in a string. The first is the charAt method:

'cat'.charAt(1) // returns "a"

Extension to ECMAScript: The other way is to treat the string as an array, where each index corresponds to an individual character:

'cat'[1] // returns "a"

[edit] Static properties

String.prototype
An object that contains string properties and methods.

[edit] Static methods

String.fromCharCode
Returns a string created from the specified sequence of Unicode values.

[edit] Properties

constructor
A reference to the String constructor.
length
The length of the string.

[edit] Methods

[edit] Methods unrelated to HTML

charAt
Returns the character at the specified index.
charCodeAt
Returns a number indicating the Unicode value of the character at the given index.
concat
Combines the text of two strings and returns a new string.
indexOf
Returns the index of the first occurrence of the specified value, or -1 if not found.
lastIndexOf
Returns the index of the last occurrence of the specified value, or -1 if not found.
match
Used to match a regular expression against a string.
quote
Encloses the string in double quotes and escapes any possible quote characters in the string.
replace
Returns the result of replacing a substring matched by a regular expression with a new specified string.
search
Returns the location of a substring matched by a specified regular expression.
slice
Extracts a section of a string and returns a new string.
split
Returns the result of splitting this string into an array of strings by separating the string into substrings.
substr
Returns a specified amount of characters beginning at a specified index.
substring
Returns the characters in a string between two specified indexes.
toLowerCase
Returns the string lowercased.
toSource
Returns a string representing the source code of the this string object. Overrides the Object.prototype.toSource method.
toString
Returns the string's primitive value. Overrides the Object.prototype.toString method.
toUpperCase
Returns the calling string value converted to uppercase.
valueOf
Returns the string's primitive value. Overrides the Object.prototype.valueOf method.

[edit] Methods related to HTML

anchor
Returns an A tag with the NAME attribute set to this string.
big
Returns this string encased with BIG tags.
blink
Returns this string encased with BLINK tags.
bold
Returns this string encased with B tags.
fixed
Returns this string encased with TT tags.
fontcolor
Returns this string encased with FONT tags with the COLOR attribute set to a specified string.
fontsize
Returns this string encased with FONT tags with the SIZE attribute set to a specified string.
italics
Returns this string encased with I tags.
link
Returns an A tag with the HREF attribute set to this string.
small
Returns this string encased with SMALL tags.
strike
Returns this string encased with STRIKE tags.
sub
Returns this string encased with SUB tags.
sup
Returns this string encased with SUP tags.