Text Split: The Two-Keystroke Function That Turns a Blob Into a Table
TLDR
Converting delimited text blobs into structured table rows requires splitting content on row and column delimiters. Handling single-space delimiters using regex whitespace matchers (\s+) prevents empty cell insertion bugs caused by consecutive spaces.
| Split Configuration | Processing Method | Whitespace Handling | Output Structure |
|---|---|---|---|
Literal Space (' ') | Standard str.split(' ') | Generates empty string cells | Broken jagged table |
Regex Whitespace (\s+) | Regex str.split(/\s+/) | Collapses consecutive spaces | Clean 2D Grid Cells |
Literal space character splits generate empty string artifacts in jagged table grids
Users often paste pipe-delimited or space-delimited text blocks into single table cells. Converting these unstructured text blobs into tabular rows requires performing a two-pass split (first by row breaks, then by column delimiters).
However, splitting space-delimited text using a literal space character (' ') creates empty cells wherever consecutive spaces exist.
Regex whitespace matchers collapse consecutive spaces to guarantee a clean grid structure
We implemented a helper function that handles space and empty-string delimiter edge cases before constructing new DOM rows:
TEXT BLOB: "John Doe 34"
LITERAL SPACE SPLIT (str.split(' ')):
┌──────┬──┬──┬──┬─────┬──┬──┬────┐
│ John │ │ │ │ Doe │ │ │ 34 │ <-- 8 Columns! (5 empty artifacts)
└──────┴──┴──┴──┴─────┴──┴──┴────┘
REGEX WHITESPACE SPLIT (str.split(/\s+/)):
┌──────┬─────┬────┐
│ John │ Doe │ 34 │ <-- Clean 3 Columns!
└──────┴─────┴────┘
Here is the implementation of the dual-pass splitting logic:
// Two-pass delimiter splitting logic
export function splitCellText(rawText, rowDelim, colDelim) {
const safeSplit = (text, delimiter) => {
if (delimiter === ' ') return text.trim().split(/\s+/); // Collapse consecutive spaces
if (delimiter === '') return [text]; // No-op for empty strings
return text.split(delimiter);
};
const lines = safeSplit(rawText, rowDelim).filter(line => line.trim() !== ''); return lines.map(line => safeSplit(line, colDelim).map(cell => cell.trim()).filter(cell => cell !== '') ); }
The resulting 2D array replaces the original cell's row in the DOM and appends subsequent rows cleanly using <tr> insertions.
Rule of thumb: Use /\s+/ regex matchers for space-delimited text splits to prevent empty cell generation.