/ javascript

String.split()

The String.split() method takes a String object and converts it to an Array of substrings that are split by a given separator.

String.split() also allows you to limit the number of instances to be separated by defining a limit parameter

Syntax

str.split([separator[, limit]]);

Splitting a string at each character

function strSplitter(str){
    return str.split(''); // This separates a string at each character
};
strSplitter('snippet');
//returns ["s", "n", "i", "p", "p", "e", "t"]

Try this the code snippet in your browser console.

Splitting a string at each space

function strSplitter(str){
    return str.split(' '); // This separates a string at each space
};
strSplitter('This is a string');
//returns ["This", "is", "a", "string"]

Try this the code snippet in your browser console.

Splitting a string at each comma

function strSplitter(str){
    return str.split(','); // This separates a string at each comma
};
strSplitter('Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday');
//returns ["Sunday", " Monday", " Tuesday", " Wednesday", " Thursday", " Friday", " Saturday"]

Try this the code snippet in your browser console.

Splitting a string using a limit

function strSplitter(str){
    return str.split('-', 3); // This separates a string at each hyphen, returning the first 3 items 
};
strSplitter('8-0-8-5-5-5-1-2-3-4');
//returns ["8", "0", "8"]

Try this the code snippet in your browser console.