将字符串拆分为数组是特定方式

时间:2019-06-09 09:06:37

标签: javascript

我有这样的字符串:

  

这是文本[SPACE],也是文本[SPACE]更多文本[SPACE]   这里文字

我的目标是创建这样的数组:

['This is a text', '[SPACE]', 'and this also text', '[SPACE]', 'more text', '[SPACE]']

或者这样

['This is a text', 'SPACE', 'and this also text', 'SPACE', 'more text', 'SPACE']

我试图像.split('[')一样拆分它,但这并不是我想要的

1 个答案:

答案 0 :(得分:2)

以正则表达式匹配并捕获 [SPACE]split中捕获的组将包含在输出数组中,因此,这正是您应该针对的目标。要忽略[SPACE]周围的空格,只需在捕获组之外正常匹配它们,它们就不会出现在输出中:

const input = 'This is a text [SPACE] and this also text [SPACE] more text [SPACE] here text';
console.log(
  input.split(/ *(\[SPACE\]) */)
);

相关问题