split Keeps Trailing Empties
split keeps trailing empties by default; the limit argument truncates and discards the remainder; matchAll preserves capture groups.
Code
const row = "a,b,c,,";
const fields = row.split(",");
console.log(fields.length, JSON.stringify(fields)); // 尾部空串保留
// limit 只保留前 n 段,余量直接丢弃(想要保留请自行 slice+join 或不用 limit)
console.log(JSON.stringify(row.split(",", 3)));
// 空分隔符:按 UTF-16 码元逐个切开,增补字符会被劈开
console.log("ab👍".split("").map((c) => c.codePointAt(0)));
// 正则带捕获组:组也进结果数组
console.log("key=value".split(/=(.+)/));
// 需要重叠或分组上下文时用 matchAll 而不是 split
for (const m of "x=1;y=2".matchAll(/(\w)=(\d)/g)) {
console.log(m[1], m[2]);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
5 ["a","b","c","",""]
["a","b","c"]
[ 97, 98, 55357, 56397 ]
[ 'key', 'value', '' ]
x 1
y 2What the code does
The loop for (const m of "x=1;y=2".matchAll(/(\w)=(\d)/g)) is the only repeated construct.
Everything operates on top-level bindings: row, fields.
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
Applying it
Expect labeled output — ab👍, key=value — when the file runs.
Statements that matter
const fields = row.split(",");
const row = "a,b,c,,";
Interactive Tools for This Topic
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. Its state lives in module-level bindings: `row`, `fields`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.