To split a string into an array of substrings in JavaScript:

  1. Use the String.split() method.
  2. Pass an optional separator as a parameter. The default separator is an empty string (" ") that splits the string between words.
  3. Specify an optional second parameter to limit the number of matches.
  4. The String.split() method returns a new array and does not change the original string.

Examples

The String.split() method splits the string every time it matches against a set of characters provided as an argument.

If you have a comma-separated string, you could split it into an array like the 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' ]

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?

Read this article to learn more about converting a string into an array using JavaScript.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.