The String object in JavaScript. The String object represents a series of characters in a string.

Basic Usage

A string primitive is treated like source code, while a String object is streated like a character sequence object. In general use a string primitive instead of a String object because if you need a String method, JavaScript will take the string primitive, automatically reserve memory for a temporary String object, run the method, and then free the memory address.

s1 = new String('2 + 2');   // creates a String object. Usually you want a primitive:
s2 = '2 + 2';               // creates a string primitive
s3 = String('2+2');         // creates a string primitive
eval(s1);                   // returns the string "2 + 2"
eval(s1.valueOf());         // returns the number 4, i.e. converted to a string primitive
eval(s2);                   // returns the number 4
eval(s3);                   // returns the number 4

Properties

.length

Implemented: JS 1.0; ECMA-262.
Returns the number of characters in the string. For an empty string, length is 0.

Methods

None of these methods mutate this, i.e. string instance which called the method. These methods usually return a new string or some other value.

As of 2008, Mozilla seems to be thinking about adding these methods:

  • .localeCompare(str). Compares the sort order of the two string.
  • .quote(). Wraps the string in double quotes. Probably does not do escaping.
  • .toLocaleLowerCase().
  • .toLocaleLowerCase().

HTML wrapping methods

These methods simply wrap the corresponding HTML tag around the string. They are practically deprecated.

var s = 'foo';
s.anchor('nameValue');     // returns '<A NAME="nameValue">foo</A>'
s.big();                   // returns '<BIG>foo</BIG>
s.blink();                 // returns '<BLINK>foo</BLINK>
s.bold();                  // returns '<B>foo</B>
s.fixed();                 // returns '<TT>foo</TT>
s.fontcolor('colorValue'); // returns '<FONT COLOR="colorValue">foo</FONT>'
s.italics();               // returns '<I>foo</I>
s.link('URL');             // returns '<A HREF="URL">foo</A>'
s.small();                 // returns '<SMALL>foo</SMALL>
s.strike();                // returns '<STRIKE>foo</STRIKE>
s.sub();                   // returns '<SUB>foo</SUB>
s.sup();                   // returns '<SUP>foo</SUP>

RegExp related methods

These are methods that can take a RegExp as a parameter. Note that the separator parameter of .split() can be a string or a regular expression.

.match(regularExpression)

Implemented: JS 1.3; ECMA-262 3.
Matches a string with a given regularExpression. Returns an array of matches or null. If the g flag is used, it is like multiple applications of RegExp.match().

'abcABC'.match(/b/);    // returns 'b'
'abcABC'.match(/B/);    // returns 'B'
'abcABC'.match(/b/ig);  // returns ['b', 'B']

.replace(regularExpression, newSubStringOrFunction)

Implemented: JS 1.2; JS 1.3 2nd paramter can be function as welll; ECMA-262 3.
Matches regularExpression, replaces matches with the newSubStringOrFunction, and returns it as a new string. If the 2nd parameter is a function (i.e. a "lambda expression"), then the function should return a strin to replace with. If no matches, then replace returns the original string.

The newSubStringOrFunction can contain the following special replacement patterns:

  • $$. Inserts a "$".
  • $`. Inserts the portion of the string that precedes the matched substring.
  • $'. Inserts the portion of the string that follows the matched substring.
  • $&. Inserts the matched substring.
  • $n or $nn. Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.
'abcABC'.replace(/b/ig, 'X');       // returns 'XbcXBC'
'abc'.replace(/x/, 'z');            // returns 'abc' since no match
"Toys 'R' Us".replace(/'/g, "''");  // returns "Toys ''R'' Us"
'veryX'.replace(/X/, ", $` rich");  // returns 'very, very rich'
'give meXmoney'.replace(/X/, " $', $$weet "); // returns 'give me money, $weet money '
'John Smith'.replace(/(\w+)\s(\w+)/, "$& become $2, $1"); // returns 'John Smith becomes Smith, John'
function replacer(sub, p1, p2, idx, str){
    return '['+'sub: '+sub+". p1: "+p1+". p2: "+p2+
'. idx: '+idx+'. str: '+ str+']';
}
'01XXzzz7'.replace(/(X+)(z+)/g, replacer);
// Above returns '01[sub: XXzzz. p1: XX. p2: zzz. idx: 2. str: 01XXzzz7]7'

.search(regularExpression)

Implemented: JS 1.2; ECMA-262 3.
Finds regularExpression and returns the index if found, else returns -1. This method is faster than .match(), but the latter is more powerful.

'abcABC'.search(/b/ig); // returns 1

.split([StringOrRegExSeparator[, nMaxNumberOfSplits]])

Implemented: JS 1.1; ECMA-262.
The string object usually has at least 1 instance of the separator. This methods takes the string, tries to split it into substrings along the separator, and returns an array of the substrings. The separator can be a string or a regular expression. If the separator is not specified or not found, then the method returns an array with 1 element for the entire string.

'a b c'.split();            // returns 'a b c'
'a b c'.split(' ');         // returns ['a', 'b', 'c']
'a b c'.split(' ', 12);     // returns ['a', 'b']
'Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand '.split(/\s*;\s*/);
// returns ['Harry Trump', 'Fred Barney', 'Helen Rigby', 'Bill Abel', 'Chris Hand']

Miscellany

Other methods of the String object

.charAt(index)

Implemented: JS 1.0; ECMA-262.
Returns the character at the index indicated. The first letter is at 0 and the last is at one less than the length. Returns an empty string if the given index is out of range.EG:

'cat'.charAt(1); // returns 'a'
// treating the string like an array is available in most variations of JS, but not ECMAScript:
'cat'[1];        // returns 'a'

.charCodeAt([index])

Implemented: JS 1.2; JS 1.3 returns Unicode instead of ISO Latin 1; ECMA-262.
Returns the Unicode character code for the character at index=0 or the index provided.

'ABC'.charCodeAt(0); // returns 65

.concat(string2[, ... stringN])

Implemented: JS 1.2; ECMA-262.
Combines the string object with 1 or more provided strings and returns a new string.

'a'.concat('b', 'c'); // returns 'abc'

.fromCharCode(num1, ..., numN)

Implemented: JS 1.2; JS 1.3 uses Unicode instead of ISO Latin 1; ECMA-262.
Static method
Returns a string constructed of the given Unicode character codes.

String.fromCharCode(65,66,67); // returns 'ABC'

.indexOf(findString[, startingIndex])

Implemented: JS 1.0; ECMA-262.
Searches forward from either the startingIndex or from the first character and returns the index if findString is found, otherwise it returns -1.

'wowwee'.indexOf('w');      // returns 0
'wowwee'.indexOf('w', 1);   // returns 2

.lastIndexOf(findString, startingIndex)

Implemented: JS 1.0; ECMA-262.
Searches backward from either the startingIndex or from the last character and returns the index if findString is found, otherwise it returns -1.

'wowwee'.lastIndexOf('w');      // returns 3
'wowwee'.lastIndexOf('w', 3);   // returns 2

.slice([startIndex[, endIndex]])

Implemented: JS 1.0; ECMA-262 3.
Extracts a portion of the string (including the startIndex but before the endIndex) and returns it as a new string. The startIndex index defaults to 0. The endIndex defaults to length. Negative indexes are offsets from the end of the string. Similar to .substr, but without any funkiness.

var s = '012345';
s.slice();      // returns '012345'
s.slice(-1);    // returns '5'
s.slice(0);     // returns '012345'
s.slice(1);     // returns '12345'
s.slice(-1,-1); // returns ''
s.slice(-1,0);  // returns ''
s.slice(-1,3);  // returns ''
s.slice(0,-1);  // returns '01234'
s.slice(0,0);   // returns ''
s.slice(0,3);   // returns '012'
s.slice(1,-1);  // returns '1234'
s.slice(1,0);   // returns ''
s.slice(1,3);   // returns '12'
s.slice(3,1);   // returns ''

.substr([startIndex[, nCharacters]])

Implemented: JavaScript 1.0; JScript 3; ECMA-262 not.
Extracts a portion of the string (starting from the startIndex for nCharacters. The startIndex defaults to 0. If the start index is negative, then it is an offset from the end of the string. If nCharacters is omitted, then it extracts from the start index to the end of the string. If nCharacters is 0 or negative, then .substr returns an empty string EG: strX.substr(-1) returns the last character.

var s = '012345';
s.substr();      // returns '012345'
s.substr(-1);    // returns '5'
s.substr(0);     // returns '012345'
s.substr(1);     // returns '12345'
s.substr(-1,-1); // returns ''
s.substr(-1,0);  // returns ''
s.substr(-1,3);  // returns '5'
s.substr(0,-1);  // returns ''
s.substr(0,0);   // returns ''
s.substr(0,3);   // returns '012'
s.substr(1,-1);  // returns ''
s.substr(1,0);   // returns ''
s.substr(1,3);   // returns '123'
s.substr(3,1);   // returns '3'

.substring([indexA[, indexB]])

Implemented: JS 1.0; ECMA-262.
Returns a subset of the current string (including indexA to before indexB) and returns a new string.

  • If indexA equals indexB, then .substring returns empty string.
  • If indexB is omitted, then .substring extracts characters to the end of the string.
  • If either argument is less than 0 or is NaN, then it is treated as if it were 0.
  • If either argument is greater than the length, then it is treated as if it were length.
  • If indexA is larger than indexB, then the effect of .substring is as if the two arguments were swapped.
var s = '012345';
s.substring();      // returns '012345'
s.substring(-1);    // returns '012345'
s.substring(0);     // returns '012345'
s.substring(1);     // returns '12345'
s.substring(-1,-1); // returns ''
s.substring(-1,0);  // returns ''
s.substring(-1,3);  // returns '012'
s.substring(0,-1);  // returns ''
s.substring(0,0);   // returns ''
s.substring(0,3);   // returns '012'
s.substring(1,-1);  // returns '0'
s.substring(1,0);   // returns '0'
s.substring(1,3);   // returns '12'
s.substring(3,1);   // returns '12'

.toLowerCase()

Implemented: JS 1.0; ECMA-262.
Converts the value of the string to lowercase and returns a new string.

'ABCabc'.toLowerCase(); // returns 'abcabc'

.toUpperCase()

Implemented: JS 1.0; ECMA-262.
Converts the value of the string to UPPERCASE and returns a new string.

'ABCabc'.toUpperCase(); // returns 'ABCABC'


GeorgeHernandez.comSome rights reserved