The syntax of this method is as follows: string.split(separator, limit).
Where string therefore represents the string to be divided. The separator parameter is mandatory and indicates which element to use to perform the division (for example, a blank space, a comma, a dash). The limit parameter is optional and represents the number of subdivisions to be made. Therefore items that go beyond this limit will not be included in the split.
This method is supported on all browsers.
Let’s now make some simple examples of use.
So we take a simple sentence as input and then with the split method we divide it using space as a separator element.
var coding = 'Programming helps the development of logical thinking'; var codingSplit = coding.split(' '); console.log(codingSplit);
In the browser console we will display an array of 7 elements, as shown below:
Array (7) [“Program”, “help”, “it”, “development”, “of”, “thought”, “logical”]
N.B. Be careful to insert empty spaces between quotes. In fact, if for example we had written:
var coding = 'Programming helps the development of logical thinking'; var codingSplit = coding.split(''); console.log(codingSplit);
As a result we would have obtained the subdivision by letter and therefore in our case an array of 49 elements:
Array (49) [“P”, “r”, “o”, “g”, “r”, “a”, “m”, “m”, “a”, “r”, …]
Let’s change the sentence, adding a second thought after the comma, as in the example below:
As a result we will see in the browser console an array of 2 elements: