gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:56:44 28 4
gpt4 key购买 nike

我有这样的字符串:

This is a text [SPACE] and this also text [SPACE] more text [SPACE] here text

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

['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('['),但这并不完全是我想要的

最佳答案

匹配并捕获正则表达式中的[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\]) */)
);

关于javascript - 将字符串拆分为数组是特定方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56513317/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com