String

Did you know that you can read content offline by using one of these tools? If you would like to read offline MDN content in another format, let us know by commenting on Bug 665750.

Dash App

Redirected from String Redirect 2

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

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:

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:

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'
        ],
        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

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:

Methods

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.
contains

Determines whether one string may be found within another string.

endsWith
Determines whether a string ends with the characters of another 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

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.
startsWith
Determines whether a string begins with the characters of another string.
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

Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the Object.prototype.toSource method.
toString
Returns a string representing the specified object. Overrides the Object.prototype.toString method.
toUpperCase
Returns the calling string value converted to uppercase.
trim
Requires JavaScript 1.8.1
Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard.
trimLeft
Requires JavaScript 1.8.1
Trims whitespace from the left side of the string.
trimRight
Requires JavaScript 1.8.1
Trims whitespace from the right side of the string.
valueOf
Returns the primitive value of the specified object. Overrides the Object.prototype.valueOf method.

HTML wrapper methods

Non-standard

Should we change these to point to our own docs rather than W3C? In any case, they're staying as is for now because with the current structure of the HTML pages here at MDC, we cannot reference specific attributes as necessary anyway (e.g., the difference between the anchor method and the link method). 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="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.

Examples

String conversion

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]));
}

Extending strings

It's possible to extend the functionality of all strings by altering the native String.prototype object.  This will 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) + "!!!");

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)

See also

Tags (7)