split method
The split method splits a string
into an array by a delimiter (separator)
in the form of
regular expression.
The method takes a regex as the first parameter, and the maximum number of elements in the resulting array as the second optional parameter.
Syntax
string.split(regular expression, [limit]);
Example
Let's split the string into an array by
the delimiter '-' or by the
delimiter '+':
let str = 'a-b+c-d+e';
let res = str.split(/[-+]/);
console.log(res);
The code execution result:
['a', 'b', 'c', 'd', 'e']
Example
Let's limit the number of elements in the resulting array:
let str = 'a-b+c-d+e';
let res = str.split(/[-+]/, 3);
console.log(res);
The code execution result:
['a', 'b', 'c']
See also
-
the
testmethod
that checks a string -
the
matchmethod
that searches for matches in a string -
the
matchAllmethod
that searches for all matches in a string -
the
execmethod
that performs a sequential search -
the
replacemethod
that performs search and replacement -
the
searchmethod
that performs a search