Doing the `.split()` with Javascript

Doing the `.split()` with Javascript

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:

"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.

"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.

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, 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.

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.

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

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

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.

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


One response to “Doing the `.split()` with Javascript”

  1. I am making a list of resources for the trainees in my team about Javascript. Your articles will fit perfectly in those, keep sharing such resourceful and informative articles.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.