split method in JavaScript regular expressions
In this lesson, we will analyze the
split
method, which is already familiar to
you - it splits a string into an array
by a separator. You should already know
that the separator is passed as a
parameter and it is a string.
However, this is not always the case - a regular expression can also be passed as a parameter. In this case, the separator will be all substrings that fall under the regular expression.
In the following example, we will split
a string into an array by the '-'
delimiter or by the '+'
delimiter:
let str = 'a-b+c-d+e';
let res = str.split(/[-+]/);
As a result, the following will be written to the variable:
['a', 'b', 'c', 'd', 'e']
Given a string with date and time:
let str = '2025-12-31 12:59:59';
Split this string so that all parts of the date and time are in the same array. That is, you should get the following array:
['2025', '12', '31', '12', '59', '59'];