Last updated: Mar 4, 2024
Reading timeยท5 min
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.
const str = 'a-b_c-d'; const arr = str.split(/[-_]+/); console.log(arr); // ๐๏ธ ['a', 'b' , 'c', 'd']
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:
Name | Description |
---|---|
separator | The pattern describing where each split should occur. |
limit | An 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.
[]
are called a character class and match either one of the provided characters.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.
The following code sample splits by a space and a dot.
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
.
const str = 'a.b c.d'; const arr = str.split(/\.|\s/); console.log(arr); // ๐๏ธ ['a', 'b', 'c', 'd']
|
(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.
This is a two-step process:
String.replaceAll()
method to replace the separators with a single,
unified character.String.split()
method to split the string on the unified character.const str = 'one.two three.four'; const arr = str .replaceAll('.', '$') .replaceAll(' ', '$') .split('$'); console.log(arr); // ๐๏ธ ['one', 'two', 'three', 'four']
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.
$
doesn't matter in this example, it could be any character, e.g. a comma or a hyphen.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.
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:
Alternatively, you could chain calls to the String.split()
and Array.join()
methods.
// โ 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']
The first call to the split()
method splits the string on each dot.
We then join the string with a dollar sign separator.
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.
This is a two-step process:
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.
You can learn more about the related topics by checking out the following tutorials: