Javascript String Split Example | Str.split() Tutorial

Javascript String Split Example Tutorial is today’s leading topic. The split() method is used to split the string into an array of the substring and returns a new collection. If the empty string (“”) is used as the separator, the string is split between each character. The split() method does not mutate the original string.

Javascript String Split Example Tutorial

The syntax is following for String Split Example.
string.split(separator, limit)

Syntax Explanation


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 welookups.com and enjoy coding';
const res = str.split(' ', 5);

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');

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 = 'welookups ';

const fields = input.split('~');


#Destructuring Arrays

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); // Aditya singh
console.log(street); // 123 Street
console.log(unit); // Apt 4
console.log(city); // France
console.log(state); // FR
console.log(zip); // 12345