Regular expressions and text guides

String split with regex: captures and empty fields

Understand why split inserts capture groups and why filtering empty fields can corrupt records.

Nav Tools ·

Compare capturing and noncapturing separators

JavaScript split inserts captured separator groups into the result array. A noncapturing group does not add those fields.

If you only want to divide values, choose the noncapturing form or a plain character class.

'a,b;c'.split(/([,;])/) → ['a',',','b',';','c']
'a,b;c'.split(/[,;]/)   → ['a','b','c']

Preserve meaningful empty positions

An empty field between separators can mean a missing value. A trailing separator also produces a final empty string.

Filtering truthy values shifts columns and changes meaning. Keep positions unless the input format explicitly discards empty fields.

'a,,c,'.split(',') → ['a','','c','']

Know what the limit does

The split limit caps the number of returned elements. It does not return an unsplit remainder as the last element.

For a key=value format that allows equals signs in the value, find the first separator and slice around it instead.

'a=b=c'.split('=',2) → ['a','b']
The final c is not included.

Choose a parser for quoted formats

This behavior is useful for simple separators, not a complete parser for CSV, escaped fields or nested syntax.

Use the existing CSV tools for quoted records. In application code, test leading, trailing and consecutive separators before adopting a split rule.

References

← Regular expressions and text guides