# How to split a string in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Apr 8, 2021, updated Aug 12, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-string-split

> A quick guide to the String.split() method in JavaScript and how to use it to split a string into an array.

To split a [string into an array](https://attacomsian.com/blog/javascript-convert-string-to-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.
3. 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:

```javascript
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:

```javascript
const str = 'lion, fox, dog, panda';

const animals = str.split(', ');

console.log(animals);

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

White space as a delimiter works too:

```javascript
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:

```javascript
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:

```javascript
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](https://attacomsian.com/blog/javascript-convert-string-to-array) to learn more about converting a string into an array using JavaScript.
