Doing the `.split()` with Javascript
Tags: javascript, todayilearned, beginners
Published: 2020-12-21 15:29:50

---
title: Doing the `.split()` with Javascript
published: true
date: 2020-12-05 23:57:45 UTC
tags: javascript, todayilearned, beginners
canonical_url: https://shannoncrabill.com/blog/split-javascript-method/
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/kmkibr2q9sggsbjow9we.jpg
---

I recently learned that the `.split()` method in Javascript can take in an _optional second argument that is the number of times it’ll split a given string_. It’ll ignore everything _after_ the string has been split that number of times, even if there are additional matches.

In this post, I will explain how `split()` works, the arguments it takes in, and some example use cases.

## Understanding `.split()`

If you are unfamiliar with `.split()` in Javascript, it is a built-in method for breaking up a string into multiple parts, based on the character(s) that you define. This is the format for `.split()` is as follows:

```javascript
"string to split".split("character[s]_to_split_by", numTimesToSplit)
```

The parts that make up a valid `.split()` method are:

- The string, or variable that references a string to be split. **Required**.
- A character or string to use as the point of reference on where to split the string. **Required**.
- A positive integer of the number of splits to make, after which `.split()` will stop evaluating the string. **Optional**.

Using the format above, if I wanted to split the string `"I love tacos!"` so that each word is its own string, I can do the following.

```javascript
"I love tacos!".split(" ")
```

Which would return `['I', 'love', 'tacos!']`. The original string is split on each empty space `" "`.

Assigning `"I love tacos!"` to a variable `string`, returns the same result.

```javascript
let string = "I love tacos!"
string.split(" ")
```

## Using the Optional `limit` Argument

Where I found using the optional _limit_ argument helpful was if I wanted to split a string into separate variables, but didn’t need all of the string I was calling the function on.

Let’s say I had copy and pasted some [HTML colors names](https://htmlcolorcodes.com/color-names/), to use in an app I’m building. Each row contains the named color, it’s hex and rgb values. Picking a few samples, and putting each row as it’s own array item, we have something that looks like this.

```javascript
const data = [
    "Gold #FFD700 rgb(255, 215, 0)",
    "Indigo #4B0082 rgb(75, 0, 130)",
    "Chartreuse #7FFF00 rgb(127, 255, 0)",
    "WhiteSmoke #F5F5F5 rgb(245, 245, 245)"
]
```

Splitting each array item on each word break (`" "`), returns this.

```javascript
['Gold', '#FFD700', 'rgb(255,', '215,', '0)']
['Indigo', '#4B0082', 'rgb(75,', '0,', '130)']
['Chartreuse', '#7FFF00', 'rgb(127,', '255,', '0)']
['WhiteSmoke', '#F5F5F5', 'rgb(245,', '245,', '245)']
```

This works. But it’s a little messy if we don’t care about the RGB values.

If we pass in `2` as the second argument `.split()` will ignore everything after it’s made two split groups. If we call `.split(" ", 2)` on each array item, the return looks like this instead.

```javascript
['Gold', '#FFD700']
['Indigo', '#4B0082']
['Chartreuse', '#7FFF00']
['WhiteSmoke', '#F5F5F5']
```

## Use Cases

Here’s another example where using the _limit_ argument with `.split()` is useful.

Let’s say we have a bunch of phone numbers as strings and we want to assign the area code to its own variable. If our phone numbers are formatted like `"555-867-5309"`, we can split on each hyphen.

```javascript
let phone = "555-867-5309"
let areaCode = phone.split("-")
```

It works, but now `areaCode` returns `['555', '867', '5309']`. With one small change to the above code, we can cleanly assign the area code to it’s own variable and ignore the rest of the phone number.

```javascript
let phone = "555-867-5309"
let areaCode = phone.split("-", 1)
```

After we’ve made `1` split on the first hyphen, the `.split()` operation stops. `areaCode` now returns `['555']`.

## Additional Information

`.split()` can break strings into smaller parts, but here are some additional things to keep in mind.

- You can split by more than one character
- The character[s] to split by are case sensitive
- Using `.split()` does not modify the original string
- `.split()` can be used together with other built-in methods like `.join()`

## Resources

- [String.prototype.split()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)
- [What is a real world use case for splitting a string in JavaScript?](https://www.quora.com/What-is-a-real-world-use-case-for-splitting-a-string-in-JavaScript)
- [Array.prototype.join()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join)

The post [Doing the `.split()` with Javascript](https://shannoncrabill.com/blog/split-javascript-method/) appeared first on [Shannon Crabill — Front End Software Engineer](https://shannoncrabill.com/blog).