The syntax is following for String Split Example.
The first argument to the split function is the string which specifies the points where the split has to take place.
This argument can be treated as the simple string or as the regular expression. If the separator is unspecified, then the whole string becomes a single array element. The same thing also happens when a separator is not present in the string. If the separator is an empty string (“”), then every character of the string is separated.
The second argument to a function limit defines an upper limit on the number of splits to be found in a given string. If a string remains unchecked after a threshold or limit is reached, then it is not reported in an array.
The return value
The split() function returns an array of strings that is formed after splitting a given string at each point where the separator occurs.
Let us take an example in Node.js and see how we can use split.
Create one file called the server.js and add the following code.
// server.js const str = 'Browse appdividend.com and enjoy coding'; const res = str.split(' ', 5); console.log(res);
Now, run the above script using the following command.
So, in the above example, we have split the string with space and limit is 5.
We can also split the string with a particular letter. Use a letter as a separator. Let us take an example.
// server.js const str = 'Browse appdividend.com and enjoy coding'; const res = str.split('appdividend'); console.log(res);
So, The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to do each split.
Let us take another example.
// server.js const input = 'krunallathiya~25 ankitlathiya~24 rushabhrupani~12345'; const fields = input.split('~'); console.log(fields);
We can also the destructure the array after converting the string into an array.
// server.js const input = 'krunal lathiya~123 Street~Apt 4~New York~NY~12345'; const [name, street, unit, city, state, zip] = input.split('~'); console.log(name); // krunal lathiya console.log(street); // 123 Street console.log(unit); // Apt 4 console.log(city); // New York console.log(state); // NY console.log(zip); // 12345