Search [Enter] to search. Click anywhere to close.

December 3rd, 2021

How To Split A String In JavaScript

You may be wondering how to split a string in JavaScript.

This is a fairly simple operation, with two main approaches used to achieve this goal.

In this article, we’ll look at using split as well as slice. These functions each have different use-cases and different return types, we’ll step through them in turn.

So let’s begin!

Split a string by a specific character

Splitting up a string based on a specific character is a fairly common operation within JavaScript.

Based on a string that looks like this: red, green, blue.

If we were to split the string by the comma character (or the ,), we’d expect 3 substrings as a result. Those substrings being red, blue and green.

There’s a JavaScript method to handle this exact scenario — split, let’s take a look.

Using the split method to split your string to an array

As the name implies, split will break apart the supplied string into an array of one or more substrings.

Where the string is split is based on the separator supplied. The separator is simply a character (or group of characters) whereby the string should be partitioned.

In the example above we used the comma as our separator, here, we’ll use the pipe or bar symbol (|) instead:

const locations = "england|ireland|scotland|wales"
// ["england", "ireland", "scotland", "wales"]

As you can see, splitting the locations string here returns an array. The array is populated with the various substrings, as demonstrated.

Using split without a separator or delimiter argument

The split method can accept two possible arguments: the separator (the first argument), as we’ve seen. But also a limit (the second argument). We’ll go over what the limit argument does in a moment.

Firstly, however, it’s worth noting that both of these arguments are optional, and thus can actually be omitted.

So it’s possible to invoke split on a string like this:

const someString = "I am a string"
// ["I am a string"]

Splitting a string without the separator argument just returns an array containing only the original string.

Using split with a delimiter (or limit) argument

The second optional argument to the split method is the limit, which effectively determines how many times the string should be split apart given the separator provided.

Here’s an example of this:

const colours = "red,green,blue,yellow,black,grey,purple"
console.log(colours.split(",", 3))
// ["red", "green", "blue"]

console.log(colours.split(",", 5))
// ["red", "green", "blue", "yellow", "black"]

When using the limit argument, items after the supplied index are excluded entirely.

This can come in really handy when you’re only interested in a specific portion of the target string. You can easily return an array containing only the data that is specifically required as per your implementation, without the need to manually filter out the rest.

Splitting the string with multiple separators

Splitting a string in JavaScript using multiple characters as a separator works in exactly the same way as if you were to use a single character:

const letters = "abcdefghijklm"
// ["abc", "ghijklm"]

Here we’re using a separator that’s 3 characters in length (“def”), and as you can see, the results are exactly what we’d expect.

It works just like when using a single character separator.

Split doesn’t modify the original string

It’s important to note that split doesn’t actually modify the target string in any way.

It returns a new array of substrings.

So to actually use the array of substrings, you’ll need to firstly assign the new substring array to its own variable:

const names = "Alan,Tom,Sarah"
const splitNames = names.split(",")

console.log(names) // "Alan,Tom,Sarah
console.log(splitNames) // ["Alan", "Tom", "Sarah"]

The value of names doesn’t change, it doesn’t become an array after invoking split upon it. This is an immutable operation, we’ll go into what that means shortly.

Split a string into two variables directly

You can make good use of ES6’s destructuring assignment to assign the values returned by your split directly to the required variables:

const items = "toothbrush,comb"
const [firstItem, secondItem] = items.split(",")

console.log(firstTime) // toothbrush
console.log(secondItem) // comb

As you can see, destructuring provides a really efficient and clean way to assign the substrings directly. Note that this isn’t specific to assigning only two variables as we are doing here, it’ll work for any number of variables.

So the array values (the results of items.split) are unpacked and assigned to the listed variables (firstItem, secondItem) in only one line.

This is one of the main benefits of using the destructuring assignment facility that ES6 provides. It’s neat and concise!

With mismatching substring to variable counts

Note how this works when we have a mismatching number of variables in comparison with the amount of substrings returned by the split method:

const shapes = "circle,square,rectangle,triangle"
const [circle, square] = items.split(",")

// Only the first 2 substrings are actually used
console.log(circle) // circle
console.log(square) // square

// There is no 5th substring to assign to the hexagon var
// items.split returns only 4 substrings
const [circle, square, rectangle, triangle, hexagon] = items.split(",")
console.log(hexagon) // undefined

So it’s fine to pass fewer variables, it just means that the remaining substrings aren’t assigned at all. No issues here.

However, if you pass more variables than there are substrings — you’ll see that the “extra” variables remain undefined. That’s because if there are 5 variables to assign to, but only 4 substrings returned by items.split — there is nothing to assign to the “extra” variable!

This won’t throw any errors or anything like that, but it’s just something to be aware of when assigning variables directly in this manner.

Split a string and get the first or last element directly

You can also assign the first element or the last element directly using methods like shift and pop.

To assign the first element from the split string, you can simply use shift, as follows:

const shapes = "circle,square,rectangle,triangle"
const firstShape = shapes.split(",").shift() // circle

And to get the last element of the split string, you can do the same thing — but using pop instead:

const shapes = "circle,square,rectangle,triangle"
const lastShape = shapes.split(",").pop() // triangle

Shift and pop are generally quite handy methods. They don’t modify the original array at all, much like slice, so shifting and poping on a sliced string (ie. an array) is an immutable operation with no unwanted side-effects.

Split a string at index or position

Of course, there may be cases when you want to split a string into pieces based upon a specific position or index.

So you may want the first 3 characters of a string, or the last 3 characters, or 2 characters starting from position 4.

Fortunately, there’s also a method to conveniently handle this in JavaScript, too. Let’s take a look.

Using slice to split a string

The slice method is really useful. It accepts two parameters, start and stop.

Here’s how it’s used:

const address = "11 Fictional Street"
console.log(address.slice(0, 5)) // 11 Fi

As you may have guessed, the very first argument to the slice method is the starting index. This refers to the position (or index) where we want to start cutting down the string from.

The second argument determines where we want to stop cutting down the string.

Given this, and as demonstrated, starting to slice at a position of 0 and ending at a position of 5 means we’ll retrieve the first 5 letters of the target string.

Unlike split, which returns an array — slice returns a new string.

Omitting the second (ending index) argument of the slice method

By omitting the second argument when using slice, you’ll simply retrieve all characters after the starting index (the first argument):

const address = "11 Fictional Street"
console.log(address.slice(6)) // tional Street

This is a fairly common operation. It’s a good way to strip out the parts of the string you aren’t interested in, and retain the rest.

Getting the last 3 (or x) characters of a string

Retrieving the first 3 characters of a string is fairly trivial, we can simply supply arguments of 0 and 3 respectively to the slice method.

To grab the last characters, however, we need a bit more logic:

const address = "11 Fictional Street"
console.log(address.slice(address.length - 3, address.length)) // eet

We just need to look at the length of the target string, and base our arguments on this.

A start argument of length - 3 means we’ll start splitting (or slicing) the string 3 characters from the end of the string.

An end argument of address.length means we’ll stop splitting at the very end of the string.

Of course, as explained, the end argument is actually optional — so we can condense our code by omitting it entirely in this case:

const address = "11 Fictional Street"
console.log(address.slice(address.length - 3)) // eet

Does slice modify the original string?

As is the case when separating the string apart with split, slice doesn’t modify the original string either.

So you need to assign the results of using the slice method to a new variable each time!

Splitting JavaScript strings: split vs slice

Now we’ve covered both split and slice, let’s compare the two and take a look at when we may use one over the other.

In short, if you need an array of substrings you’ll want to use split.

If you want to return another string as a result of your split, you’ll want to use slice, instead.

So it really depends on your implementation and your use-case.

The two methods do entirely different things, it depends on how you want to actually segregate the components of your string to begin with!

A note on immutability

In both of these cases, when using split as well as when using slice to split apart strings — it’s worth noting that these operations are both immutable.

This means that they don’t modify the original target string.

It’s for that reason that you’ll often see slice in particular used with no arguments on a string:

const myString = "My string"
const myStringCopy = myString.slice()

This may look strange at first, what’s the purpose of using slice like this?

So both strings here have a value of “My string”, but myStringCopy is a copy of myString.

We’re slicing, but not supplying any arguments. So the full string is sliced, retaining all characters — only a new string is returned now.

The new string is effectively a copy of the target string. Any further operations upon this copied string won’t mutate or update the target string.

This is an example of an immutable operation.

What’s the purpose of immutability in general?

In short, immutability promotes safer and cleaner code.

That’s because, when utilizing immutable operations, you can’t accidentally change (or mutate) the target structure accidentally. This ultimately leads to more predictable code that’s less error prone and more robust.

I’d particularly recommend this article which covers the topic of writing immutable code if you’re interested in finding out more.

Immutability is also a core concept within Functional Programming in general, so it’s well worth doing some reading on this topic, too.

In conclusion…

To summarise, we’ve looked at various approaches with regards to splitting a string in JavaScript.

Primarily using both the split and slice methods.

We’ve also looked at destructing assignment, which is an ES6 feature, as well as other ways we can directly assign substrings to variables on the fly.

I hope you’ve enjoyed this guide, please check out the JavaScript category for other similar articles!

Thanks for reading!

Have any questions? Ping me over at @justacodingblog
← Back to blog