mozilla

Revision 54317 of String

  • Revision slug: JavaScript/Reference/Global_Objects/String
  • Revision title: String
  • Revision id: 54317
  • Created:
  • Creator: JasonSpiro
  • Is current revision? No
  • Comment 0-base as should be. Edit released to PD.

Revision Content

Summary

Core Object

An object representing a series of characters in a string.

Created by

The String constructor:

new String(string)

Parameters

string 
Any string.

Description

String objects are created by calling the constructor new String():

s_obj = new String("foo"); // creates a String object

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:

s_prim = String("bar"); //creates a primitive string

Literal strings in Javascript source code create primitive strings:

s_also_prim = "foo"; // creates a primitive string

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.length;       // 3
s_prim.length;      // 3
s_also_prim.length; // 3
'foo'.length;       // 3
"foo".length;       // 3

(A string literal can use single or double quotation marks.)

String objects can be converted to primitive strings with String.valueOf().

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

You can convert the value of any object into a string using the global String function.

Accessing individual characters in a string

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

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

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

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

Note: The second way (treating the string as an array) is not part of the ECMAScript; it's a JavaScript feature.

In both cases, attempting to set an individual character won't work. Trying to set a character through charAt results in an error:

var x = 'cat';
x.charAt(0) = 'b'; // error

Setting a character via indexing does not throw an error, but the string itself is unchanged:

var x = 'cat';
x[2] = 'p';
alert(x);    // still outputs 'cat'
alert(x[2]); // still outputs 't'

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
    document.write(a + " is less than " + b);
else if (a > b)
    document.write(a + " is greater than " + b);
else
    document.write(a + " and " + b + " are equal.");

Properties

  • constructor: Specifies the function that creates an object's prototype.
  • length: Reflects the length of the string.
  • prototype: Allows the addition of properties to a String object.

Static methods

  • fromCharCode: Returns a string created by using the specified sequence of Unicode values.

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.
  • match: Used to match a regular expression against a string.
  • 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.
  • toLowerCase: Returns the calling string value converted to lowercase.
  • toSource: Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the Object.toSource method.
  • toString: Returns a string representing the specified object. Overrides the Object.toString method.
  • toUpperCase: Returns the calling string value converted to uppercase.
  • valueOf: Returns the primitive value of the specified object. Overrides the Object.valueOf method.

HTML wrapper methods

Each of the following methods returns a copy of the string wrapped inside an HTML tag. For example, "test".bold() returns "<b>test</b>".

These methods are of limited use, as they provide only a subset of the available HTML tags and attributes.

Examples

Example: String primitive

The following statement creates a string primitive from the string literal "Schaefer", and assigns it to the variable last_name:

var last_name = "Schaefer";

Example: String primitive properties

The following expressions evaluate to 8, "SCHAEFER", and "schaefer", respectively:

last_name.length
last_name.toUpperCase()
last_name.toLowerCase()

Example: Setting an individual character in a string

An individual character cannot be directly set in a string. Instead, a new string can be created using the substr or substring methods:

function setCharAt(str, index, ch) {
   return str.substr(0, index) + ch + str.substr(index + 1);
}

alert(setCharAt('scam', 1, 'p')); // outputs "spam"

Example: Pass a string among scripts in different windows or frames

The following code creates two string variables and opens a second window:

var lastName = "Schaefer";
var firstName = "Jesse";
empWindow = window.open('string2.html', 'window1', 'width=300,height=300');

If the HTML source for the second window (string2.html) creates two string variables, empLastName and empFirstName, the following code in the first window assigns values to the second window's variables:

empWindow.empFirstName = firstName;
empWindow.empLastName = lastName;

The following code in the first window displays the values of the second window's variables:

alert('empFirstName in empWindow is ' + empWindow.empFirstName);
alert('empLastName in empWindow is ' + empWindow.empLastName);
{{ wiki.languages( { "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/String", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/String" } ) }}

Revision Source

<p>
</p>
<h3 name="Summary"> Summary </h3>
<p><b>Core Object</b>
</p><p>An object representing a series of characters in a string.
</p>
<h3 name="Created_by"> Created by </h3>
<p>The String constructor:
</p>
<pre class="eval">new String(<i>string</i>)
</pre>
<h3 name="Parameters"> Parameters </h3>
<dl><dt> <code>string</code> </dt><dd> Any string.
</dd></dl>
<h3 name="Description"> Description </h3>
<p>String objects are created by calling the constructor <code>new String()</code>:
</p>
<pre class="eval">s_obj = new String("foo"); // creates a String object
</pre>
<p>The <code>String</code> object wraps Javascript's string primitive data type with the methods described below. The global function <code>String()</code> can also be called without <code>new</code> in front to create a primitive string:
</p>
<pre class="eval">s_prim = String("bar"); //creates a primitive string
</pre>
<p>Literal strings in Javascript source code create primitive strings:
</p>
<pre class="eval">s_also_prim = "foo"; // creates a primitive string
</pre>
<p>Because Javascript automatically converts between string primitives and String objects, you can call any of the methods of the <code>String</code> object on a string primitive. JavaScript automatically converts the string primitive to a temporary <code>String</code> object, calls the method, then discards the temporary <code>String</code> object. For example, you can use the <code>String.length</code> property on a string primitive created from a string literal:
</p>
<pre class="eval">s_obj.length;       // 3
s_prim.length;      // 3
s_also_prim.length; // 3
'foo'.length;       // 3
"foo".length;       // 3
</pre>
<p>(A string literal can use single or double quotation marks.) 
</p><p>String objects can be converted to primitive strings with <code>String.valueOf()</code>.
</p><p>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:
</p>
<pre class="eval">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
</pre>
<p>You can convert the value of any object into a string using the global <a href="en/Core_JavaScript_1.5_Reference/Functions/String">String</a> function.
</p>
<h4 name="Accessing_individual_characters_in_a_string"> Accessing individual characters in a string </h4>
<p>There are two ways to access an individual character in a string. The first is the <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/charAt">charAt</a> method:
</p>
<pre class="eval">'cat'.charAt(1) // returns "a"
</pre>
<p>The other way is to treat the string as an array, where each index corresponds to an individual character:
</p>
<pre class="eval">'cat'[1] // returns "a"
</pre>
<p>Note: The second way (treating the string as an array) is not part of the ECMAScript; it's a JavaScript feature.
</p><p>In both cases, attempting to set an individual character won't work. Trying to set a character through <code>charAt</code> results in an error:
</p>
<pre class="eval">var x = 'cat';
x.charAt(0) = 'b'; // error
</pre>
<p>Setting a character via indexing does not throw an error, but the string itself is unchanged:
</p>
<pre class="eval">var x = 'cat';
x[2] = 'p';
alert(x);    // still outputs 'cat'
alert(x[2]); // still outputs 't'
</pre>
<h4 name="Comparing_strings"> Comparing strings </h4>
<p>C developers have the <code>strcmp()</code> function for comparing strings. In JavaScript, you just use the less-than and greater-than operators:
</p>
<pre class="eval">var a = "a";
var b = "b";
if (a &lt; b) // true
    document.write(a + " is less than " + b);
else if (a &gt; b)
    document.write(a + " is greater than " + b);
else
    document.write(a + " and " + b + " are equal.");
</pre>
<h3 name="Properties"> Properties </h3>
<ul><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/constructor">constructor</a>: Specifies the function that creates an object's prototype.  
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/length">length</a>: Reflects the length of the string.  
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/prototype">prototype</a>: Allows the addition of properties to a String object.  
</li></ul>
<h3 name="Static_methods"> Static methods </h3>
<ul><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/fromCharCode">fromCharCode</a>: Returns a string created by using the specified sequence of Unicode values.
</li></ul>
<h3 name="Methods"> Methods </h3>
<h4 name="Methods_unrelated_to_HTML"> Methods unrelated to HTML </h4>
<ul><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/charAt">charAt</a>: Returns the character at the specified index.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/charCodeAt">charCodeAt</a>: Returns a number indicating the Unicode value of the character at the given index.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/concat">concat</a>: Combines the text of two strings and returns a new string.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/indexOf">indexOf</a>: Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/lastIndexOf">lastIndexOf</a>: Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/match">match</a>: Used to match a regular expression against a string.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/replace">replace</a>: Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/search">search</a>: Executes the search for a match between a regular expression and a specified string.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/slice">slice</a>: Extracts a section of a string and returns a new string.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/split">split</a>: Splits a String object into an array of strings by separating the string into substrings.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/substr">substr</a>: Returns the characters in a string beginning at the specified location through the specified number of characters.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/substring">substring</a>: Returns the characters in a string between two indexes into the string.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/toLowerCase">toLowerCase</a>: Returns the calling string value converted to lowercase.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/toSource">toSource</a>: Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/Object/toSource">Object.toSource</a> method.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/toString">toString</a>: Returns a string representing the specified object. Overrides the <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/Object/toString">Object.toString</a> method.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/toUpperCase">toUpperCase</a>: Returns the calling string value converted to uppercase.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/valueOf">valueOf</a>: Returns the primitive value of the specified object. Overrides the <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/Object/valueOf">Object.valueOf</a> method.
</li></ul>
<h4 name="HTML_wrapper_methods"> HTML wrapper methods </h4>
<p>Each of the following methods returns a copy of the string wrapped inside an HTML tag. For example, "test".bold() returns "&lt;b&gt;test&lt;/b&gt;".
</p>
<ul><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/anchor">anchor</a>: <a class="external" href="http://www.w3.org/TR/html401/struct/links.html#adef-name-A"><code>&lt;a name="<i>name</i>"&gt;</code></a> (hypertext target)
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/big">big</a>: <a class="external" href="http://www.w3.org/TR/html401/present/graphics.html#edef-BIG"><code>&lt;big&gt;</code></a>
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/blink">blink</a>: <code>&lt;blink&gt;</code>
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/bold">bold</a>: <a class="external" href="http://www.w3.org/TR/html401/present/graphics.html#edef-B"><code>&lt;b&gt;</code></a>
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/fixed">fixed</a>: <a class="external" href="http://www.w3.org/TR/html401/present/graphics.html#edef-TT"><code>&lt;tt&gt;</code></a>
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/fontcolor">fontcolor</a>: <code>&lt;font color="<i>color</i>"&gt;</code>
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/fontsize">fontsize</a>: <code>&lt;font size="<i>size</i>"&gt;</code>
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/italics">italics</a>: <a class="external" href="http://www.w3.org/TR/html401/present/graphics.html#edef-I"><code>&lt;i&gt;</code></a>
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/link">link</a>: <a class="external" href="http://www.w3.org/TR/html401/struct/links.html#adef-href"><code>&lt;a href="<i>url</i>"&gt;</code></a> (link to URL)
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/small">small</a>: <a class="external" href="http://www.w3.org/TR/html401/present/graphics.html#edef-SMALL"><code>&lt;small&gt;</code></a>.
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/strike">strike</a>: <a class="external" href="http://www.w3.org/TR/html401/present/graphics.html#edef-STRIKE"><code>&lt;strike&gt;</code></a>
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/sub">sub</a>: <a class="external" href="http://www.w3.org/TR/html401/struct/text.html#edef-SUB"><code>&lt;sub&gt;</code></a>
</li><li> <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/sup">sup</a>: <a class="external" href="http://www.w3.org/TR/html401/struct/text.html#edef-SUP"><code>&lt;sup&gt;</code></a>
</li></ul>
<p>These methods are of limited use, as they provide only a subset of the available HTML tags and attributes.
</p>
<h3 name="Examples"> Examples </h3>
<h4 name="Example:_String_primitive"> Example: String primitive </h4>
<p>The following statement creates a string primitive from the string literal "Schaefer", and assigns it to the variable <code>last_name</code>:
</p>
<pre class="eval">var last_name = "Schaefer";
</pre>
<h4 name="Example:_String_primitive_properties"> Example: String primitive properties </h4>
<p>The following expressions evaluate to <code>8</code>, "<code>SCHAEFER</code>", and "<code>schaefer</code>", respectively:
</p>
<pre class="eval">last_name.length
last_name.toUpperCase()
last_name.toLowerCase()
</pre>
<h4 name="Example:_Setting_an_individual_character_in_a_string"> Example: Setting an individual character in a string </h4>
<p>An individual character cannot be directly set in a string. Instead, a new string can be created using the <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/substr">substr</a> or <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/String/substring">substring</a> methods:
</p>
<pre class="eval">function setCharAt(str, index, ch) {
   return str.substr(0, index) + ch + str.substr(index + 1);
}

alert(setCharAt('scam', 1, 'p')); // outputs "spam"
</pre>
<h4 name="Example:_Pass_a_string_among_scripts_in_different_windows_or_frames"> Example: Pass a string among scripts in different windows or frames </h4>
<p>The following code creates two string variables and opens a second window:
</p>
<pre class="eval">var lastName = "Schaefer";
var firstName = "Jesse";
empWindow = window.open('string2.html', 'window1', 'width=300,height=300');
</pre>
<p>If the HTML source for the second window (<code>string2.html</code>) creates two string variables, <code>empLastName</code> and <code>empFirstName</code>, the following code in the first window assigns values to the second window's variables:
</p>
<pre class="eval">empWindow.empFirstName = firstName;
empWindow.empLastName = lastName;
</pre>
<p>The following code in the first window displays the values of the second window's variables:
</p>
<pre class="eval">alert('empFirstName in empWindow is ' + empWindow.empFirstName);
alert('empLastName in empWindow is ' + empWindow.empLastName);
</pre>{{ wiki.languages( { "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/String", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/String" } ) }}
Revert to this revision