Split with Regex
The split() method accepts a regex as delimiter, enabling complex splitting on multiple separators or patterns.
The split() method accepts a regex as delimiter, enabling complex splitting on multiple separators or patterns.
// 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"]
Wrap the regex delimiter in a capturing group to include it in the resulting array.
More in JavaScript