Table of contents
- 1. Summary
- 2. Syntax
- 3. Parameters
- 4. Description
- 4.1. Character access
- 4.2. Comparing strings
- 5. Properties
- 6. Methods
- 7. String instances
- 7.1. Properties
- 7.2. Methods
- 7.2.1. Methods unrelated to HTML
- 7.2.2. HTML wrapper methods
Summary
String is a global object that may be used to construct String instances.
Syntax
String([string])
new String([string])
String literals take the form:
'stringText'
"stringText"
Parameters
string- Any string.
stringText- Any series of characters that has been properly encoded.
Description
String objects may be created by calling the constructor new String(). The String object wraps JavaScript's string primitive data type with the methods described below. The global function String() can also be called without new in front to create a primitive string. String literals in JavaScript are primitive strings.
Because JavaScript automatically converts between string primitives and String objects, you can call any of the methods of the String object on a string primitive. JavaScript automatically converts the string primitive to a temporary String object, calls the method, then discards the temporary String object. For example, you can use the String.length property on a string primitive created from a string literal:
s_obj = new String(s_prim = s_also_prim = "foo"); s_obj.length; // 3 s_prim.length; // 3 s_also_prim.length; // 3 'foo'.length; // 3 "foo".length; // 3
(A string literal is denoted with single or double quotation marks.)
String objects can be converted to primitive strings with the valueOf method.
String primitives and String objects give different results when evaluated as JavaScript. Primitives are treated as source code; String objects are treated as a character sequence object. For example:
s1 = "2 + 2"; // creates a string primitive
s2 = new String("2 + 2"); // creates a String object
eval(s1); // returns the number 4
eval(s2); // returns the string "2 + 2"
eval(s2.valueOf()); // returns the number 4
Character access
There are two ways to access an individual character in a string. The first is the charAt method:
return 'cat'.charAt(1); // returns "a"
The other way is to treat the string as an array, where each index corresponds to an individual character:
return 'cat'[1]; // returns "a"
In both cases, attempting to set an individual character won't work. Trying to set a character through charAt results in an error, while trying to set a character via indexing does not throw an error, but the string itself is unchanged.
Comparing strings
C developers have the strcmp() function for comparing strings. In JavaScript, you just use the less-than and greater-than operators:
var a = "a"; var b = "b"; if (a < b) // true print(a + " is less than " + b); else if (a > b) print(a + " is greater than " + b); else print(a + " and " + b + " are equal.");
A similar result can be achieved using the localeCompare method inherited by String instances.
Properties
For properties inherited by String instances, see Properties of String instances.
prototype- Allows the addition of properties to a String object.
Methods
For methods inherited by String instances, see Methods of String instances.
fromCharCode- Returns a string created by using the specified sequence of Unicode values.
String instances
Properties
constructor- Specifies the function that creates an object's prototype.
length- Reflects the length of the string.
- N
- Non-standard
Used to access the character in the Nth position where N is a positive integer between 0 and one less than the value oflength. These properties are read-only.
Methods
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 within the calling String object of the first occurrence of the specified value, or -1 if not found.
lastIndexOf- Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
localeCompare- Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
match- Used to match a regular expression against a string.
quote- Non-standard
Wraps the string in double quotes ("""). replace- Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
search- Executes the search for a match between a regular expression and a specified string.
slice- Extracts a section of a string and returns a new string.
split- Splits a String object into an array of strings by separating the string into substrings.
substr- Returns the characters in a string beginning at the specified location through the specified number of characters.
substring- Returns the characters in a string between two indexes into the string.
toLocaleLowerCase- The characters within a string are converted to lower case while respecting the current locale. For most languages, this will return the same as
toLowerCase. toLocaleUpperCase- The characters within a string are converted to upper case while respecting the current locale. For most languages, this will return the same as
toUpperCase. toLowerCase- Returns the calling string value converted to lower case.
toSource- Non-standard
Returns an object literal representing the specified object; you can use this value to create a new object. Overrides theObject.toSourcemethod. toString- Returns a string representing the specified object. Overrides the
Object.toStringmethod. toUpperCase- Returns the calling string value converted to uppercase.
trim-
New in Firefox 3.5
Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard. trimLeft-
New in Firefox 3.5
Non-standard
Trims whitespace from the left side of the string. trimRight-
New in Firefox 3.5
Non-standard
Trims whitespace from the right side of the string. valueOf- Returns the primitive value of the specified object. Overrides the
Object.valueOfmethod.
HTML wrapper methods
Each of the following methods returns a copy of the string wrapped inside the appropriate HTML tag.
anchor<a name="name">(hypertext target)big<big>blink<blink>bold<b>fixed<tt>fontcolor<font color="color">fontsize<font size="size">italics<i>link<a href=/old?u=https%3A%2F%2Fdeveloper.mozilla.org%2Fen%2FJavaScript%2FReference%2FGlobal_Objects%2F%26quot%3B%3Cem&y=1999>url">(link to URL)small<small>.strike<strike>sub<sub>sup<sup>
These methods are of limited use, as they provide only a subset of the available HTML tags and attributes.
Object:__defineGetter__, __defineSetter__, eval, hasOwnProperty, isPrototypeOf, __lookupGetter__, __lookupSetter__, __noSuchMethod__, propertyIsEnumerable, toLocaleString, unwatch, watch