split Handles Regex Separators And Limits

split accepts a regex so alternation splits on several separators at once, capture groups keep the separators, and the limit argument caps the piece count.

JavascriptData Integrity

Code

javascriptsnippet
22 lines
const log = 'a,b;c'.split(/[,;]/);
console.log('regex alternation :', JSON.stringify(log));

// 分隔符正则里的捕获组会被保留:分隔符本身留在结果里
const kept = 'a,b'.split(/(,)/);
console.log('capture keeps sep :', JSON.stringify(kept));

// 字符串分隔符没有这个行为:', ' 原样消失
const plain = 'a, b'.split(', ');
console.log('plain separator   :', JSON.stringify(plain));

// limit 只截取前 n 段,剩余内容不再切割
const capped = 'a,b,c'.split(',', 2);
console.log('limit 2           :', JSON.stringify(capped));

// 空字符串按单字符切分;空分隔符得到 ['']
console.log("'' split ','      :", JSON.stringify(''.split(',')));
console.log("'ab' split ''      :", JSON.stringify('ab'.split('')));

// split('') 按码元切分会拆散代理对:用 Array.from 按码点切
console.log('split breaks pair :', JSON.stringify('a😊b'.split('').length));
console.log('Array.from keeps  :', JSON.stringify(Array.from('a😊b')));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

regex alternation : ["a","b","c"]
capture keeps sep : ["a",",","b"]
plain separator   : ["a","b"]
limit 2           : ["a","b"]
'' split ','      : [""]
'ab' split ''      : ["a","b"]
split breaks pair : 4
Array.from keeps  : ["a","😊","b"]

What the code does

Module-level bindings hold the data — log, kept, plain, capped — with no function scope in between.

Watch out for

  • The dependency list is empty; the language runtime covers it all.

Applying it

Output lines are prefixed (regex alternation :, capture keeps sep :, plain separator :), making each step’s effect easy to spot.

Statements that matter

const capped = 'a,b,c'.split(',', 2);
const log = 'a,b;c'.split(/[,;]/);
const plain = 'a, b'.split(', ');

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. Its state lives in module-level bindings: `log`, `kept`, `plain`.