How to Split a String by a Regex in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Split a String by a Regex in JavaScript #

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str.split(/[,.\s]/). The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.

index.js
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() method is the separator.

The method splits the string into an array of substrings on each match of the regular expression.

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, a dot, and a whitespace.

If you need a regex cheatsheet, check out the one from MDN. It's by far the best one out there.

Character classes are most commonly used when you need to split the string using multiple separators.

Here's another example that splits a string on each digit.

index.js
const str = 'one1two2three'; const result = str.split(/\d/); console.log(result); // 👉️ ['one', 'two', 'three']

The \d special character matches any digit 0-9. It's the same as using a range [0-9].

Note that you don't have to pass the g (global) flag when using the split method with a regular expression. This is because the method does not stop on the first occurrence.

However, you could use other flags. For example, you can use the i flag for a case insensitive match.

index.js
const str = 'oneAtwoBthree'; const result = str.split(/[ab]/i); console.log(result); // 👉️ ['one', 'two', 'three']

The character class [] matches either a or b. We set the i flag, so we match uppercase and lowercase occurrences of the a and b characters in the string.

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.