How to split a string in JavaScript

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.


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


// [ '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(', ');


// [ 'lion', 'fox', 'dog', 'panda' ]

White space as a delimiter works too:

const str = 'lion fox dog panda';

const animals = str.split(' ');


// [ '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('');


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


// [ '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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.