This JavaScript tutorial is designed to help the JavaScript programmer solve problems using the JavaScript split function with strings and lists. The purpose of the JavaScript string.split function is to break up a string of items into an array (or list).
By the same token, one would expect a similar list split function to exist to cut up an array, but this is not the case. Instead JavaScript has a non-destructive array.slice function that extracts parts of an array into a new, smaller, array. The article shall look at how this can be used to split the array into two pieces.
First, however, the string.split function should be explained.
The split function is available in three possible variations:
The first variation of string.split is possibly the most common and easiest to use. It will split using the comma as a separator:
Sometimes, however, the string might be logically arranged with different separators, and so the second variation can be used:
Note that it is also possible to provide multiple characters and even regular expressions in the separators parameter, thereby allowing the items in the resulting string pieces to be treated before they are placed in the array.
The final variation allows the programmer to split the string into pieces, but stop after a predetermined number of split have been performed. So, to perform the JavaScript split two times, code such as the following would be used:
In the above snippet, the resulting array would only contain the first two items from the string. In all cases, the separator is discarded.
The array that results from the split operation contains a number of items, each of which is a string. The most common thing that the programmer subsequently needs to do is to count pieces of the list with the array.length function.
Of course, the individual lengths of each item in the list can be obtained by using the array.length function. So, to obtain the total number of characters, the code would be akin to:
By a similar token, a double for loop could be used to pass over each character in the array of strings.
Another useful function is the array.toString function, which will create a comma separated string from the array of strings - it is the reverse of the split function, but the programmer can not specify a separator other than the default.
Finally, there is an interesting function that can be used to split a list (array) of strings into two lists.
Since there is no array.split function, it is necessary to use the array.slice function instead. The general form is:
The begin and end parameters are the start and end points for the split. The end can be omitted, in which case everything from the begin point up to the end of the array is returned.
The function is also non-destructive so if an array needs to be split into two pieces, then the programmer would need to do the JavaScript 'split' two times in order to achieve the correct result. The original array is not modified in the array.slice call.