You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按特定规则将含[SPACE]标记的字符串拆分为数组?

解决字符串按[SPACE]拆分并保留分隔符的问题

你遇到的问题我懂,普通的split方法确实搞不定——它会直接丢弃分隔符,而且单纯按[拆分肯定不是你要的结果。别担心,咱们用正则表达式的捕获组就能轻松实现你想要的数组结构,下面分两种情况给你具体方案:

情况1:保留[SPACE]作为数组元素

用带捕获组的正则表达式拆分,split会把匹配到的分隔符也当成数组元素保留下来,之后过滤掉空元素就行:

const originalStr = "This is a text [SPACE] and this also text [SPACE] more text [SPACE]";
const splitResult = originalStr.split(/(\[SPACE\])/).filter(item => item.trim() !== '');
console.log(splitResult);
// 输出: ['This is a text', '[SPACE]', 'and this also text', '[SPACE]', 'more text', '[SPACE]']

为啥这么做?

  • /(\[SPACE\])/ 是正则表达式,括号()是捕获组,专门匹配完整的[SPACE](注意[和]是正则里的特殊字符,得用\转义才能匹配原本的符号);
  • 普通split会丢分隔符,但用了捕获组之后,分隔符会被保留成独立的数组元素;
  • 加filter是为了去掉拆分后可能出现的空字符串或者纯空格的元素(比如原字符串开头/结尾有多余空格的情况)。

情况2:把[SPACE]转成SPACE作为数组元素

如果想要简化分隔符,有两种简单的实现方式:

方式一:先替换再拆分

先把所有[SPACE]替换成SPACE,再用同样的捕获组拆分逻辑:

const originalStr = "This is a text [SPACE] and this also text [SPACE] more text [SPACE]";
const modifiedStr = originalStr.replace(/\[SPACE\]/g, 'SPACE');
const splitResult = modifiedStr.split(/(SPACE)/).filter(item => item.trim() !== '');
console.log(splitResult);
// 输出: ['This is a text', 'SPACE', 'and this also text', 'SPACE', 'more text', 'SPACE']

方式二:拆分后再处理元素

先按[SPACE]拆分,再把每个分隔符元素的方括号去掉:

const originalStr = "This is a text [SPACE] and this also text [SPACE] more text [SPACE]";
const splitResult = originalStr.split(/(\[SPACE\])/)
  .filter(item => item.trim() !== '')
  .map(item => item.replace(/\[|\]/g, ''));
console.log(splitResult);
// 同样能得到你想要的数组

这样就能完美实现你要的数组结构啦!

内容的提问来源于stack exchange,提问作者NickD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:07:47