String.split()

The JavaScript String.split() method allows you to split a string into an array of substrings.

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

Slicing a String

var str = "Welcome to Code Snippet."

str.slice(11, -1)
// returns "Code Snippet"

==NOTE: no
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.

Help us improve our content