The String.split()
method is used to convert a string into an array of substrings and returns the new array. It does not change the original string.
It splits the string every time it matches against a set of characters provided as an argument. You can also pass an optional second parameter to limit the number of matches.
Examples
If you have a comma-separated string, you could split it into an array like below:
const str = 'lion,fox,dog,panda';
const animals = str.split(',');
console.log(animals);
// [ 'lion', 'fox', 'dog', 'panda' ]
The delimiter
argument could be anything: dashes, underscores, and even spaces after commas:
const str = 'lion, fox, dog, panda';
const animals = str.split(', ');
console.log(animals);
// [ 'lion', 'fox', 'dog', 'panda' ]
Just white-space as a delimiter works too:
const str = 'lion fox dog panda';
const animals = str.split(' ');
console.log(animals);
// [ 'lion', 'fox', 'dog', 'panda' ]
You can also pass in an empty string as a delimiter. In this case, the string will be split between each character:
const str = 'lion';
const chars = str.split('');
console.log(chars);
// [ 'l', 'i', 'o', 'n' ]
Limiting the number of results
To limit the number of items in your array, just pass in an integer as a second argument to specify the number of splits:
const str = 'lion,fox,dog,panda';
const animals = str.split(',', 3);
console.log(animals);
// [ 'lion', 'fox', 'dog' ]
Browser compatibility
The String.split()
method works in all modern browsers and back to at least IE 6.
What's next?
Take a look at this article to learn more about different ways of converting a string into an array using JavaScript.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.