String.split() (Method)

Split a string and store the components in an array.

Availability:

ECMAScript edition - 2
JavaScript - 1.1
JScript - 3.0
Internet Explorer - 4.0
Netscape - 3.0
Netscape Enterprise server - 2.0
Opera - 3.0
Property/method value type:Array object
JavaScript syntax:-myString.split(aPattern)
-myString.split(aSeparator)
-myString.split(aSeparator, aCount)
Argument list:aPatternA regular expression to define the splitting sequence
aSeparatorA separator string to use for slicing the string
aCountAn iterator count to limit the number of splits

This method returns an array that contains the separated elements.

The string is split using the separator string and each separate item is stored in an array element. The items in the array are ordered in the same sequence they were presented in the original string.

This method is the complement of the join() method that is applied to arrays.

The separator string is used to sub-divide the target string and is removed from the string component entities that result. The original string can be reconstructed by using the same separator in an Array.join() operation.

If the separator string is omitted, then the string is simply stored in the first element of a new array without being split. This is not the same as specifying an empty string. That will cause the split to happen but because you have specified an empty string, and there is an empty string between each character, the string will turned into an array of individual characters. This is amazingly useful sometimes.

In JavaScript version 1.2, this method is extended to allow the use of a regular expression as its argument. The match looks for the splitting delimiter. Using a constant character string inside the regular expression is functionally identical to using a string as the splitting value. Where this becomes powerful is where a character class or matching expression is used.

The example shows how a string of letters separated by a variety of numeric digits can be split apart using a regular expression. This would be very difficult to do any other way and would require many more lines of code.

Example code:

   <HTML>
   <HEAD>
   </HEAD>
   <BODY>
   <SCRIPT>
   myRegExp = new RegExp("[0-9]", "g");
   myString = "A0B1C2D3E4F5G";
   myArray = myString.split(myRegExp);
   for(myEnum=0; myEnum < myArray.length; myEnum++)
   {
   document.write(myArray[myEnum]);
   document.write("<BR>");
   }
   </SCRIPT>
   </BODY>
   </HTML>

See also:Array object, Array.join(), RegExp pattern, RegExp.exec(), Regular expression, String concatenate (+), String.match(), String.prototype, String.replace(), String.search(), String.slice(), String.substr(), String.substring()

insert figure 0027

Cross-references:

ECMA 262 edition 2 - section - 15.5.4.8

ECMA 262 edition 3 - section - 15.5.4.14