Back

String

String

Properties

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

Methods

str.charAt()
Returns the character at the specified index.
str.charCodeAt()
Returns a number indicating the Unicode value of the character at the given index.
str.concat()
Combines the text of two strings and returns a new string.
str.indexOf()
Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
str.lastIndexOf()
Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
str.localeCompare()
Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
str.match()
Used to match a regular expression against a string.
str.replace()
Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
str.search()
Executes the search for a match between a regular expression and a specified string.
str.slice()
Extracts a section of a string and returns a new string.
str.split()
Splits a String object into an array of strings by separating the string into substrings.
str.substr()
Returns the characters in a string beginning at the specified location through the specified number of characters.
str.substring()
Returns the characters in a string between two indexes into the string.
str.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().
str.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().
str.toLowerCase()
Returns the calling string value converted to lower case.
str.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.
str.toString()
Returns a string representing the specified object. Overrides the Object.prototype.toString() method.
str.toUpperCase()
Returns the calling string value converted to uppercase.
str.trim()
Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard.
str.trimLeft()
Trims whitespace from the left side of the string.
str.trimRight()
Trims whitespace from the right side of the string.
str.valueOf()
Returns the primitive value of the specified object. Overrides the Object.prototype.valueOf() method.

  Created by Mozilla Contributors, license: CC-BY-SA 2.5

y returning the object. For example:

var s1 = '2 + 2';             // creates a string primitive
var 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

String.prototype
Allows the addition of properties to a String object.

Methods

String.fromCharCode()
Returns a string created by using the specified sequence of Unicode values.

String generic methods

String generics are non-standard, deprecated and might get removed in the future. Note that you can not rely on them cross-browser without using the shim that is provided below.

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;
console.log(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

Methods unrelated to HTML

HTML wrapper methods

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 (var i = 0, n = inputValues.length; i < n; ++i) {
  outputStrings.push(String(inputValues[i]));
}

  Created by Mozilla Contributors, license: CC-BY-SA 2.5