Skip to main content
Module 7 · Lesson 4 of 428/32 in the course~16 min
Module lessons (4/4)

Split with regex

Lesson preview5 hands-on exercises readyRegex Course · Module 7 — Flags, substitution, split

Split a string on a pattern (permissive CSV, minimal tokenizer).

What you'll learn in this lesson

  • Tokenize dirty strings by passing a regex as a separator to String.prototype.split(regex, limit).
  • Also preserve the delimiters in the result array by enclosing the separator in a capturing group (...).
  • Handle the second argument limit and empty elements in the margins when the separator appears at the beginning or end.

Overview

String.prototype.split(separator, limit) doesn't just accept fixed characters like ",": by passing a regex as a separator you can split irregularly spaced text, multiple separators (;, ,, \t) and intelligent parsers.

Normally split cuts the string where the pattern matches and throws away the separator. But if that pattern contains at least one capture group (...), JavaScript inserts the captured values into the result array exactly between one fragment and another!

Sections covered in this lesson

  1. 1Mental model: smart scissors with optional capture
  2. 24 progressive examples step by step
  3. 3Guided practical exercises
  4. 4Quick check
Pro Lesson · Module 7 — Flags, substitution, split

Unlock "Split with regex" and the full Regex Course curriculum

Split a string on a pattern (permissive CSV, minimal tokenizer).

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Regex Course plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.