String

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"

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, and checking for the existence or location of substrings with the substring and substr methods.

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 and 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

Properties

For properties available on String instances, see Properties of String instances.

prototype
Allows the addition of properties to a String object.
Properties inherited from Function:
arity, caller, constructor, length, name

Methods

For methods available on String instances, see Methods of String instances.

fromCharCode
Returns a string created by using the specified sequence of Unicode values.
Methods inherited from Function:
apply, call, toSource, toString

String instances

Properties

constructor
Specifies the function that creates an object's prototype.
length
Reflects the length of the string.
N
Used to access the character in the Nth position where N is a positive integer between 0 and one less than the value of length. These properties are read-only.
Properties inherited from Object:
constructor

Methods

constructor
Specifies the function that creates an object's prototype.
length
Reflects the length of the string.
N
Used to access the character in the Nth position where N is a positive integer between 0 and one less than the value of length. These properties are read-only.
Properties inherited from Object:
constructor

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

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 0.2 (Yes) 9.0 (Yes) (Yes)
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)

Tags (6)

Contributors to this page: lmorchard, Fredchat, ethertank, Johnjbarton, Prodoc, Ptak82, Deltab, hapalibashi, evilpie, JohnJBarton1, Roebot, Sevenspade, Brettz9, daguej, satyr, Potappo, Neil, Sheppy, Mar, Geary, teoli, Chris Chittleborough, Andr3w, grendel, Marcoos, JasonSpiro, Hongli, Shoe, Mgjbot, Maian, Dria
Last updated by: ethertank,
Last reviewed by: ethertank,