String

  • Revision slug: Web/JavaScript/Reference/Global_Objects/String
  • Revision title: String
  • Revision id: 443083
  • Created:
  • Creator: ethertank
  • Is current revision? Да
  • комментировать

Revision Content

Summary

The String global object is a constructor for strings, or a sequence of characters.

Syntax

String literals take the forms:

'string text'
"string text"
"中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ"

Or, using the String global object directly:

String(thing)
new String(thing)

Parameters

thing
Anything to be converted to a string.

Description

Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their length, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the indexOf method, or extracting substrings with the substring method.

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-like object, where individual characters correspond to a numerical index:

return 'cat'[1]; // returns "a"
Array-like character access (the second way above) is not part of ECMAScript 3. It is a JavaScript and ECMAScript 5 feature.

For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See Object.defineProperty for more information.)

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.

Distinction between string primitives and String objects

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of booleans and numbers.)

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

var s_prim = "foo";
var s_obj = new String(s_prim);

console.log(typeof s_prim); // Logs "string"
console.log(typeof s_obj);  // Logs "object"

String primitives and String objects also give different results when using eval. Primitives passed to eval are treated as source code; String objects are treated as all other objects are, by returning the object. For example:

s1 = "2 + 2";               // creates a string primitive
s2 = new String("2 + 2");   // creates a String object
console.log(eval(s1));      // returns the number 4
console.log(eval(s2));      // returns the string "2 + 2"

For these reasons, code may break when it encounters String objects when it expects a primitive string instead, although generally authors need not worry about the distinction.

A String object can always be converted to its primitive counterpart with the valueOf method.

console.log(eval(s2.valueOf())); // returns the number 4
Note: For another possible approach to strings in JavaScript, please read the article about StringView – a C-like representation of strings based on typed arrays.

Properties

{{Js_see_prototype("String", "Properties")}}

prototype
Allows the addition of properties to a String object.
{{jsOverrides("Function", "Properties", "prototype")}}

Methods

{{Js_see_prototype("String", "Methods")}}

fromCharCode
Returns a string created by using the specified sequence of Unicode values.
{{jsOverrides("Function", "Methods", "fromCharCode")}}

String generic methods

The String instance methods are also available in Firefox as of JavaScript 1.6 (though not part of the ECMAScript standard) on the String object for applying String methods to any object:

var num = 15;
alert(String.replace(num, /5/, '2'));

Generics are also available on Array methods.

The following is a shim to provide support to non-supporting browsers:

/*globals define*/
// Assumes all supplied String instance methods already present (one may use shims for these if not available)
(function () {
    'use strict';

    var i,
        // We could also build the array of methods with the following, but the
        //   getOwnPropertyNames() method is non-shimable:
        // Object.getOwnPropertyNames(String).filter(function (methodName) {return typeof String[methodName] === 'function'});
        methods = [
            'quote', 'substring', 'toLowerCase', 'toUpperCase', 'charAt',
            'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith',
            'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase',
            'toLocaleUpperCase', 'localeCompare', 'match', 'search',
            'replace', 'split', 'substr', 'concat', 'slice', 'fromCharCode'
        ],
        methodCount = methods.length,
        assignStringGeneric = function (methodName) {
            var method = String.prototype[methodName];
            String[methodName] = function (arg1) {
                return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
            };
        };

    for (i = 0; i < methodCount; i++) {
        assignStringGeneric(methods[i]);
    }
}());

String instances

Properties

{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}

Methods

{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods')}}

Non-native methods

It's possible to extend the native String.prototype object with some non-native utilities. Here are some examples.

Repeat a string

String.prototype.repeat = function (nTimes) {
  var sDiff = "", sBase2 = nTimes > 0 ? this.valueOf() : "";
  for (var nMask = nTimes; nMask > 1; nMask >>= 1) {
    if (nMask & 1) { sDiff += sBase2; }
    sBase2 += sBase2;
  }
  return sBase2 + sDiff;
};

// alert("Albert said:" + " no".repeat(4) + "!!!");

Example

It's possible to use String as a "safer" toString alternative, as although it still normally calls the underlying toString, it also works for null and undefined. For example:

var outputStrings = [];
for (let i = 0, n = inputValues.length; i < n; ++i) {
  outputStrings.push(String(inputValues[i]));
}

Browser compatibility

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 0.2 {{CompatVersionUnknown}} 9.0 {{CompatVersionUnknown}} {{CompatVersionUnknown}}
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}

See also

Revision Source

<h2 id="Summary" name="Summary">Summary</h2>
<p>The <code>String</code> global object is a constructor for strings, or a sequence of characters.</p>
<h2 id="Syntax" name="Syntax">Syntax</h2>
<p>String literals take the forms:</p>
<pre class="syntaxbox">
'string text'
"string text"
"中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ"</pre>
<p>Or, using the <code>String</code> global object directly:</p>
<pre class="syntaxbox">
String(thing)
new String(thing)</pre>
<h3 id="Parameters" name="Parameters">Parameters</h3>
<dl>
  <dt>
    <code>thing</code></dt>
  <dd>
    Anything to be converted to a string.</dd>
</dl>
<h2 id="Description" name="Description">Description</h2>
<p>Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length">length</a></code>, to build and concatenate them using the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/String_Operators">+ and += string operators</a>, checking for the existence or location of substrings with the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf">indexOf</a></code> method, or extracting substrings with the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring">substring</a></code> method.</p>
<h3 id="Character_access" name="Character_access">Character access</h3>
<p>There are two ways to access an individual character in a string. The first is the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt"><code>charAt</code></a> method:</p>
<pre class="brush: js">
return 'cat'.charAt(1); // returns "a"
</pre>
<p>The other way is to treat the string as an array-like object, where individual characters correspond to a numerical index:</p>
<pre class="brush: js">
return 'cat'[1]; // returns "a"
</pre>
<div class="note">
  Array-like character access (the second way above) is not part of ECMAScript 3. It is a JavaScript and ECMAScript 5 feature.</div>
<p>For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code> for more information.)</p>
<h3 id="Comparing_strings" name="Comparing_strings">Comparing strings</h3>
<p>C developers have the <code>strcmp()</code> function for comparing strings. In JavaScript, you just use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">less-than and greater-than operators</a>:</p>
<pre class="brush: js">
var a = "a";
var b = "b";
if (a &lt; b) // true
  print(a + " is less than " + b);
else if (a &gt; b)
  print(a + " is greater than " + b);
else
  print(a + " and " + b + " are equal.");
</pre>
<p>A similar result can be achieved using the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare"><code>localeCompare</code></a> method inherited by <code>String</code> instances.</p>
<h3 id="Distinction_between_string_primitives_and_String_objects">Distinction between string primitives and <code>String</code> objects</h3>
<p>Note that JavaScript distinguishes between <code>String</code> objects and primitive string values. (The same is true of <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean">booleans</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects">numbers</a>.)</p>
<p>String literals (denoted by double or single quotes) and strings returned from <code>String</code> calls in a non-constructor context (i.e., without using the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> keyword</a>) are primitive strings. JavaScript automatically converts primitives to <code>String</code> objects, so that it's possible to use <code>String</code> object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.</p>
<pre class="brush: js">
var s_prim = "foo";
var s_obj = new String(s_prim);

console.log(typeof s_prim); // Logs "string"
console.log(typeof s_obj);  // Logs "object"
</pre>
<p>String primitives and <code>String</code> objects also give different results when using <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval">eval</a></code>. Primitives passed to <code>eval</code> are treated as source code; <code>String</code> objects are treated as all other objects are, by returning the object. For example:</p>
<pre class="brush: js">
s1 = "2 + 2";               // creates a string primitive
s2 = new String("2 + 2");   // creates a String object
console.log(eval(s1));      // returns the number 4
console.log(eval(s2));      // returns the string "2 + 2"
</pre>
<p>For these reasons, code may break when it encounters <code>String</code> objects when it expects a primitive string instead, although generally authors need not worry about the distinction.</p>
<p>A <code>String</code> object can always be converted to its primitive counterpart with the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/valueOf"><code>valueOf</code></a> method.</p>
<pre class="brush: js">
console.log(eval(s2.valueOf())); // returns the number 4
</pre>
<div class="note">
  <strong>Note:</strong> For another possible approach to strings in JavaScript, please read the article about <a href="/en-US/docs/Web/JavaScript/Typed_arrays/StringView" title="/en-US/docs/Web/JavaScript/Typed_arrays/StringView"><code>StringView</code> – a C-like representation of strings based on typed arrays</a>.</div>
<h2 id="Properties" name="Properties">Properties</h2>
<h4 id=".7B.7BJs_see_prototype(.22String.22.2C_.22Properties.22).7D.7D">{{Js_see_prototype("String", "Properties")}}</h4>
<dl>
  <dt>
    <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype"><code>prototype</code></a></dt>
  <dd>
    Allows the addition of properties to a String object.</dd>
</dl>
<div>
  {{jsOverrides("Function", "Properties", "prototype")}}</div>
<h2 id="Methods" name="Methods">Methods</h2>
<h4 id=".7B.7BJs_see_prototype(.22String.22.2C_.22Methods.22).7D.7D">{{Js_see_prototype("String", "Methods")}}</h4>
<dl>
  <dt>
    <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode"><code>fromCharCode</code></a></dt>
  <dd>
    Returns a string created by using the specified sequence of Unicode values.</dd>
</dl>
<div>
  {{jsOverrides("Function", "Methods", "fromCharCode")}}</div>
<h2 id="String_generic_methods"><code>String</code> generic methods</h2>
<p>The <code>String </code>instance methods are also available in Firefox as of JavaScript 1.6 (though not part of the ECMAScript standard) on the String object for applying String methods to any object:</p>
<pre class="brush: js">
var num = 15;
alert(String.replace(num, /5/, '2'));
</pre>
<p class="brush: js"><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Array_generic_methods">Generics</a> are also available on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array"><code>Array</code></a> methods.</p>
<p class="brush: js">The following is a shim to provide support to non-supporting browsers:</p>
<pre class="brush: js">
/*globals define*/
// Assumes all supplied String instance methods already present (one may use shims for these if not available)
(function () {
    'use strict';

    var i,
        // We could also build the array of methods with the following, but the
        //   getOwnPropertyNames() method is non-shimable:
        // Object.getOwnPropertyNames(String).filter(function (methodName) {return typeof String[methodName] === 'function'});
        methods = [
            'quote', 'substring', 'toLowerCase', 'toUpperCase', 'charAt',
            'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith',
            'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase',
            'toLocaleUpperCase', 'localeCompare', 'match', 'search',
            'replace', 'split', 'substr', 'concat', 'slice', 'fromCharCode'
        ],
        methodCount = methods.length,
        assignStringGeneric = function (methodName) {
            var method = String.prototype[methodName];
            String[methodName] = function (arg1) {
                return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
            };
        };

    for (i = 0; i &lt; methodCount; i++) {
        assignStringGeneric(methods[i]);
    }
}());</pre>
<h2 id="String_instances" name="String_instances"><code>String</code> instances</h2>
<h3 id="Properties">Properties</h3>
<p>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}</p>
<h3 id="Methods">Methods</h3>
<p>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods')}}</p>
<h3 id="Non-native_methods">Non-native methods</h3>
<p>It's possible to extend the native <code>String.prototype</code> object with some non-native utilities. Here are some examples.</p>
<h4 id="Repeat_a_string">Repeat a string</h4>
<pre class="brush: js">
String.prototype.repeat = function (nTimes) {
  var sDiff = "", sBase2 = nTimes &gt; 0 ? this.valueOf() : "";
  for (var nMask = nTimes; nMask &gt; 1; nMask &gt;&gt;= 1) {
    if (nMask &amp; 1) { sDiff += sBase2; }
    sBase2 += sBase2;
  }
  return sBase2 + sDiff;
};

// alert("Albert said:" + " no".repeat(4) + "!!!");</pre>
<h3 id="Example">Example</h3>
<p>It's possible to use <code>String</code> as a "safer" <code><a href="/en-US/docs/toString">toString</a></code> alternative, as although it still normally calls the underlying <code>toString</code>, it also works for <code>null</code> and <code>undefined</code>. For example:</p>
<pre class="brush: js">
var outputStrings = [];
for (let i = 0, n = inputValues.length; i &lt; n; ++i) {
  outputStrings.push(String(inputValues[i]));
}
</pre>
<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2>
<div>
  {{CompatibilityTable}}</div>
<div id="compat-desktop">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Chrome</th>
        <th>Firefox (Gecko)</th>
        <th>Internet Explorer</th>
        <th>Opera</th>
        <th>Safari (WebKit)</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>0.2</td>
        <td>{{CompatVersionUnknown}}</td>
        <td>9.0</td>
        <td>{{CompatVersionUnknown}}</td>
        <td>{{CompatVersionUnknown}}</td>
      </tr>
    </tbody>
  </table>
</div>
<div id="compat-mobile">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Android</th>
        <th>Firefox Mobile (Gecko)</th>
        <th>IE Phone</th>
        <th>Opera Mobile</th>
        <th>Safari Mobile</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>{{CompatVersionUnknown}}</td>
        <td>{{CompatVersionUnknown}}</td>
        <td>{{CompatVersionUnknown}}</td>
        <td>{{CompatVersionUnknown}}</td>
        <td>{{CompatVersionUnknown}}</td>
      </tr>
    </tbody>
  </table>
</div>
<h2 id="See_also">See also</h2>
<ul>
  <li><a href="/en-US/docs/Web/API/DOMString" title="/en-US/docs/Web/API/DOMString">DOMString</a></li>
  <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays/StringView" title="/en-US/docs/Web/JavaScript/Typed_arrays/StringView"><code>StringView</code> – a C-like representation of strings based on typed arrays</a></li>
</ul>
Revert to this revision