使用 JavaScript 的 split() 将字符串拆分为数组

text.split(separator, limit) 返回由各段组成的数组。字符串分隔符不会出现在结果中,原字符串保持不变。如果没有找到分隔符或省略该参数,整个字符串会保留为一项。

在分隔符处拆分

const text = 'abc,def,ghi';
console.log(text.split(','));   // ['abc', 'def', 'ghi']
console.log(text.split('def')); // ['abc,', ',ghi']
console.log(text.split('|'));   // ['abc,def,ghi']
console.log(text);              

限制数组元素的数量

limit 是数组的最大长度。设为 2 会丢弃剩余部分,设为 0 得到空数组。分隔符连续出现或在首尾出现时可能产生空项。可用 filter(part => part !== '') 删除空值,或用 map(part => part.trim()) 去掉首尾空白。请参阅 String.prototype.split()。

console.log('abc,def,ghi'.split(',', 2)); // ['abc', 'def']
console.log('abc,def,ghi'.split(',', 0)); // []
console.log('abc,def,ghi'.split());       // ['abc,def,ghi']

保留首个分隔符之后的全部文本

对 region:eu:west 调用 split(':', 2) 会丢弃 west。用 indexOf() 找到第一个冒号并按位置拆分,可以保留整个值。

{
  function splitAtFirstColon(text) {
    const index = text.indexOf(':');
    if (index === -1) return [text];
    return [text.slice(0, index), text.slice(index + 1)];
  }

  const setting = 'region:eu:west';
  console.log(setting.split(':', 2));     // ['region', 'eu']
  console.log(splitAtFirstColon(setting)); // ['region', 'eu:west']
  console.log(splitAtFirstColon('region')); // ['region']
}

输出依次是 ['region', 'eu']、['region', 'eu:west'] 和 ['region']。没有冒号时,索引为 -1,函数只返回原文本。更长的分隔符需跳过其完整长度。

运行带分隔符和上限的完整示例

将代码以 UTF-8 保存为 split-example.html 并打开。初始结果为 abc、def 和 ghi。上限为 2 时保留 abc 和 def,为 0 时返回空数组。未出现的分隔符会保留一个元素。重置可恢复输入。

表单接受 0 至 4,294,967,295 的整数。使用字符串分隔符时,API 会把显式上限转成 32 位无符号整数,过大的值可能变成较小的值。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>练习拆分字符串</title>
</head>
<body>
<label for="source">原始字符串</label>
<input id="source" type="text" value="abc,def,ghi">
<label for="separator">分隔符</label>
<input id="separator" type="text" value=",">
<label for="limit">最大项数(留空表示全部)</label>
<input id="limit" type="number" min="0" max="4294967295" step="1">
<button id="run" type="button">拆分</button>
<button id="reset" type="button">重置</button>
<pre id="output" aria-live="polite"></pre>
<script>
const source = document.querySelector('#source');
const separator = document.querySelector('#separator');
const limit = document.querySelector('#limit');
const output = document.querySelector('#output');

function show() {
  const limitText = limit.value.trim();
  const n = Number(limitText);
  if (limit.validity.badInput || (limitText !== '' && (!Number.isInteger(n) || n < 0 || n > 0xFFFFFFFF))) {
    output.textContent = '请输入 0 至 4,294,967,295 之间的整数。';
    return;
  }
  const parts = limitText === ''
    ? source.value.split(separator.value)
    : source.value.split(separator.value, n);
  output.textContent = `结果: ${JSON.stringify(parts)}\n项数: ${parts.length}`;
}

document.querySelector('#run').addEventListener('click', show);
document.querySelector('#reset').addEventListener('click', () => {
  source.value = 'abc,def,ghi';
  separator.value = ',';
  limit.value = '';
  show();
});
show();
</script>
</body>
</html>

注意 Unicode、捕获组和 CSV

空分隔符按 UTF-16(16 位 Unicode 转换格式)的代码单元拆分,可能拆开表情符号。Array.from(text) 按码点遍历。要按可见字符分段,可以使用 Intl.Segmenter 的字素分割。

console.log('a,,b,'.split(','));       // ['a', '', 'b', '']
console.log('a, b; c'.split(/[,;]\s*/)); // ['a', 'b', 'c']
console.log(Array.from('\u{1F642}')); 

使用正则表达式作分隔符时,捕获组可能进入结果。处理逗号分隔值(CSV)时,如果字段可含逗号,应使用能处理引号的解析器。请参阅 RFC 4180。