Skip to content

[Edit] JavaScript: .split() #7026

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 62 additions & 24 deletions content/javascript/concepts/strings/terms/split/split.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,72 +2,110 @@
Title: '.split()'
Description: 'Returns a new array of substrings based on a given string.'
Subjects:
- 'Web Development'
- 'Computer Science'
- 'Web Development'
Tags:
- 'Strings'
- 'Formatting'
- 'Functions'
- 'Methods'
- 'Formatting'
- 'Strings'
CatalogContent:
- 'introduction-to-javascript'
- 'paths/front-end-engineer-career-path'
---

The **`.split()`** method returns a new [array](https://www.codecademy.com/resources/docs/javascript/arrays) of substrings based on a given string.
In JavaScript, the **`.split()`** method returns a new [array](https://www.codecademy.com/resources/docs/javascript/arrays) of substrings based on a given string. This method is useful for parsing CSV data, processing user input, or breaking apart text for analysis.

## Syntax

```pseudo
string.split(separator, limit);
```

The `separator` (optional) describes the pattern where each split should occur. It may be one of the following:
**Parameters:**

- `separator` (Optional): Describes the pattern where each split should occur.
- `limit` (Optional): Determines the number of substring elements included in the returned array.

- A string of one or more characters.
- A [regular expression](https://www.codecademy.com/resources/docs/javascript/regexp).
**Return value:**

If a `separator` is not provided, the returned array will contain the entire `string` as its lone element.
The `.split()` method returns a new array of substrings based on a given string.

The `limit` (also optional) determines the number of substring elements included in the returned array.
> **Note:** If `separator` is not provided, the returned array will contain the entire `string` as its lone element.

## Example
## Example 1: Using `.split()` Without `limit`

The following example splits a string into an array of names:
This example uses the `.split()` method without the `limit` parameter to split the `stringOfNames` string into an array of names:

```js
const stringOfNames = 'Dominic, Shelly, Luka, Devin';

console.log('No limit:', stringOfNames.split(', '));
```

Here is the output:

```shell
No limit: [ 'Dominic', 'Shelly', 'Luka', 'Devin' ]
```

## Example 2: Using `.split()` with `limit`

This example uses the `.split()` method with the `limit` parameter to split the `stringOfNames` string into an array of names limited to 3 elements:

```js
const stringOfNames = 'Dominic, Shelly, Luka, Devin';

console.log('Limited to 3 elements:', stringOfNames.split(', ', 3));
```

This will log the following output:
Here is the output:

```shell
No limit: [ 'Dominic', 'Shelly', 'Luka', 'Devin' ]
Limited to 3 elements: [ 'Dominic', 'Shelly', 'Luka' ]
```

## Codebyte Example
## Codebyte Example: Using `.split()` Without Parameters

The following example showcases the `.split()` in two ways:

1. Not including a `separator` returns an `arrayOfNames` with the entire `stringOfNames` as the sole element.
2. The `arrayOfNames` is reassigned with a `separator` and then traversed with `.split()` being invoked on each name.
This example uses the `.split()` method without any parameters to split the `stringOfNames` string into an array of names in a string:

```codebyte/javascript
const stringOfNames = 'Dominic, Shelly, Luka, Devin';

let arrayOfNames = stringOfNames.split();

console.log("No separator; entire string is lone element:\n", arrayOfNames, "\n");
console.log(arrayOfNames);
```

## Frequently Asked Questions

### 1. Can I use regular expressions with `.split()`?

Yes. Regular expressions can be used with `.split()` for more flexible and complex splitting logic:

```js
// Uses the separators '-' and '_'
let substr = 'one-two_three'.split(/[-_]/);

console.log(substr); // [ 'one', 'two', 'three' ]
```

### 2. What if the separator in `.split()` is an empty string?

Splitting on an empty string using `.split()` breaks the string into an array of individual characters:

arrayOfNames = stringOfNames.split(`, `);
```js
let substr = 'ABC'.split('');

console.log(substr); // [ 'A', 'B', 'C' ]
```

### 3. What happens with consecutive separators in `.split()`?

Empty strings appear in the result if there are consecutive separators in `.split()`:

```js
let substr = 'a,,b'.split(',');

// Iterate through arrayOfNames and .split() each name string into separate characters.
for(let i = 0; i < arrayOfNames.length; i++) {
console.log(arrayOfNames[i].split(""));
};
console.log(substr); // [ 'a', '', 'b' ]
```