Wed Nov 17 2021·2 min read
Photo by Alexander Popov
To split a string by a regular expression, pass a regex as a parameter to the
split() method, e.g.
split method takes a string
or regular expression and splits the string based on the provided separator,
into an array of substrings.
const str = 'one,two.three four'; const result = str.split(/[,.\s]/); // 👇️ ['one', 'two', 'three', 'four'] console.log(result);
The only parameter we passed to the String.split is the separator.
The forward slashes
/ / mark the beginning and end of the regular expression.
The regular expression in the example uses a character class
 to match any
of the characters between the square brackets - a comma, dot, and whitespace.
If you need a regex cheatsheet, check out this one from MDN. It's by far the best one out there.
Here's another example that splits a string on each digit.
const str = 'one1two2three'; const result = str.split(/\d/); console.log(result); // 👉️ ['one', 'two', 'three']
\d special character matches any digit
0-9. It's the same as using a
g(global) flag when using the
splitmethod with a regular expression, as the method does not stop on the first occurrence.
However, you could use other flags, for example, case insensitive match.
const str = 'oneAtwoBthree'; const result = str.split(/[ab]/i); console.log(result); // 👉️ ['one', 'two', 'three']
The character class
 matches either
b. Because we've set the
flag, we match uppercase and lowercase occurrences of the
in the string.