What is the split() string method?
As the name suggests, the split() method divides a given string into an array of substrings. And finally returns this array of substrings. And the original array remains unchanged. Let us understand the syntax of this method.
let string = "test string"; string.split(separator, limit)
Let us understand each argument in the syntax.
This argument is optional. We can use the split string method even without putting a separator in the syntax. In that case, the array that is returned contains only one element that consists of the entire string. We usually put the pattern that describes where the split should occur in the string. When we put multiple characters in this argument, the entire exact sequence must be found in the string to split the string at those places.
This argument is an integer and specifies the maximum number of substrings allowed in the array. The split method stops splitting as soon as either the string is parsed completely to the limit is reached. If the limit is reached before the string is parsed completely, the rest of the string is not considered at all. When the limit value is zero, an empty array is returned. This argument is also optional like that of the separator argument.
A copy of the supplied string is split ( based on the arguments passed ) into an array. This array of strings is returned by this method.
Let us understand it with the help of some examples:
Splitting a string by each character:
let info = 'I learn coding from codedamn' console.log(info.split(''))
[ "I", " ", "l", "e", "a", "r", "n", " ", "c", "o", "d", "i", "n", "g", " ", "f", "r", "o", "m", " ", "c", "o", "d", "e", "d", "a", "m", "n"]
Now let us split the string based on space character and return an array containing the substrings.
let info = 'I learn coding from codedamn' let arr = info.split(' '); console.log(arr);
[“I”, “learn”, “coding”, “from”, “codedamn”]
We can access each element of the array by using the array methods.
Split with a limit:
We have already discussed the limit argument in the syntax. Now let us understand how it works with the help of an example
let info = 'I learn coding from codedamn' console.log(message.split(' ', 3))
[“I”, “learn”, “coding”]
If we change the limit to zero, then the returned value would be an empty array.
let info = 'I learn coding from codedamn' info.split(' ',0)
Reversing a string:
We can reverse a string using the split() method. We do it by using a chain that contains split(), reverse(), and join() methods. Let us see it with the help of an example.
const str = 'codedamn'; str.split('').reverse().join('');
The split() method splits the string into an array
The reverse() method reverses the whole array
The join() method joins back the reversed array and forms a string