SyntaxStudy
Sign Up
JavaScript Intermediate 4 min read

String split() with Regex

Split with Regex

The split() method accepts a regex as delimiter, enabling complex splitting on multiple separators or patterns.

Example
// Split on any whitespace
"hello world  foo	bar".split(/\s+/);
// ["hello", "world", "foo", "bar"]

// Split on punctuation
"one,two;three|four".split(/[,;|]/);
// ["one", "two", "three", "four"]

// Keep delimiters using a capturing group
"a1b2c3".split(/(\d)/);
// ["a", "1", "b", "2", "c", "3", ""]

// Limit results
"a,b,c,d".split(/,/, 2);
// ["a", "b"]
Pro Tip

Wrap the regex delimiter in a capturing group to include it in the resulting array.