Availability: |
| ||||||||
Property/method value type: | Array object | ||||||||
JavaScript syntax: | - | myString.split(aPattern) | |||||||
- | myString.split(aSeparator) | ||||||||
- | myString.split(aSeparator, aCount) | ||||||||
Argument list: | aPattern | A regular expression to define the splitting sequence | |||||||
aSeparator | A separator string to use for slicing the string | ||||||||
aCount | An 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.
<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>
Prev | Home | Next |
String.small() | Up | String.strike() |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. |