Split a String with multiple Separators using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 4, 2024
5 min

banner

# Table of Contents

  1. Split a String with multiple Separators in JavaScript
  2. Split a String with multiple Separators using replaceAll
  3. Split a String with multiple Separators using split and join

# Split a String with multiple Separators in JavaScript

Use the String.split() method to split a string with multiple separators, e.g. str.split(/[-_]+/).

The split method can be passed a regular expression containing multiple characters to split the string with multiple separators.

index.js
const str = 'a-b_c-d'; const arr = str.split(/[-_]+/); console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b' , 'c', 'd']

split string with multiple separators

The code for this article is available on GitHub
If you're looking to avoid using regular expressions, scroll down to the example that uses the replaceAll() method.

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

The String.split() method takes the following 2 parameters:

NameDescription
separatorThe pattern describing where each split should occur.
limitAn integer used to specify a limit on the number of substrings to be included in the array.

We passed a regular expression to the String.split() method.

The forward slashes / / mark the beginning and end of the regular expression.

The square brackets [] are called a character class and match either one of the provided characters.
index.js
const str = 'a-b_c-d'; const arr = str.split(/[-_]+/); console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b' , 'c', 'd']

In the example, we match a hyphen or an underscore.

The plus + matches the preceding item one or more times.

In the example, it matches a hyphen or an underscore one or more times.

You can adjust the separators by adding the characters you need to match between the square brackets.

The following code sample splits by a space and a dot.

index.js
const str = 'a.b c.d'; const arr = str.split(/[.\s]+/); console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'd']

The \s special character matches whitespace (spaces, tabs and newlines).

You could also use a pipe | (or) to simplify your regular expression, for example a|b matches a or b.

index.js
const str = 'a.b c.d'; const arr = str.split(/\.|\s/); console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'd']
We used a pipe | (or) symbol in our regular expression. The dot . is a special character, so we had to escape it using a backslash.

The following characters: +,-,(,),*,?,. have a special meaning in regular expressions and have to be escaped using a backslash to be interpreted as a literal character.

This code sample achieves the same result as the regex that used a character class [].

If you ever need help reading a regular expression, check out this regular expression cheat sheet by MDN.

It contains a table with the name and the meaning of each special character with examples.

If you're looking to avoid using regular expressions, use the String.replaceAll() method.

# Split a String with multiple Separators using replaceAll

This is a two-step process:

  1. Use the String.replaceAll() method to replace the separators with a single, unified character.
  2. Use the String.split() method to split the string on the unified character.
index.js
const str = 'one.two three.four'; const arr = str .replaceAll('.', '$') .replaceAll(' ', '$') .split('$'); console.log(arr); // ๐Ÿ‘‰๏ธ ['one', 'two', 'three', 'four']

split string with multiple separators using replaceall

The code for this article is available on GitHub

By replacing all occurrences of the multiple separators with the same character, we get a string with a single separator, on which we can use the split() method without any regular expressions.

This is a bit unintuitive at first, but the dollar sign $ doesn't matter in this example, it could be any character, e.g. a comma or a hyphen.
index.js
const str = 'one.two three.four'; const arr = str.replaceAll('.', '-') .replaceAll(' ', '-') .split('-'); console.log(arr); // ๐Ÿ‘‰๏ธ ['one', 'two', 'three', 'four']

All we care about is unifying the separators into a single character, which we can pass to the split() method.

You can define a reusable function if you have to do this often.

index.js
function splitMultiple(str, separators) { let replacedStr = str for (const separator of separators) { replacedStr = replacedStr.replaceAll(separator, '$') } return replacedStr.split('$') } const str = 'one.two three.four,five'; // ๐Ÿ‘‡๏ธ [ 'one', 'two', 'three', 'four', 'five' ] console.log(splitMultiple(str, ['.', ' ', ',']))

The splitMultiple function takes a string and an array of separators as parameters and splits the string into an array on each occurrence of a separator.

We used the same approach in the function:

  1. Replace all occurrences of the separators with a unified character (a dollar sign).
  2. Split the string on the unified character (the dollar sign).

# Split a String with multiple Separators using split and join

Alternatively, you could chain calls to the String.split() and Array.join() methods.

index.js
// โœ… split on each dot and space const str = 'a.b c.d'; const split3 = str .split('.') .join('$') .split(' ') .join('$') .split('$'); console.log(split3); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'd']

split string with multiple separators using split and join

The code for this article is available on GitHub

The first call to the split() method splits the string on each dot.

We then join the string with a dollar sign separator.

index.js
const str = 'a.b c.d'; // ๐Ÿ‘‡๏ธ "a$b c$d" console.log(str.split('.').join('$'));

The next step is to split by a space and join by a dollar sign again.

We are essentially replacing the dots and spaces with dollar signs, so we can unify the two separators into 1 and split using the single separator.

This is a two-step process:

  1. Replace all dots and spaces with a single character.
  2. Split the string by the single character.

I'm not a huge fan of using regular expressions, however, in this scenario, I find the regex approach to be the most intuitive.

The replaceAll() method is also easy to read, but it's a bit more indirect and takes a second to understand.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev