gpt4 book ai didi

javascript - 将给定的字符串拆分为数组

转载 作者:行者123 更新时间:2023-12-01 23:29:41 26 4
gpt4 key购买 nike

假设给定的字符串是:

[[1]] is for cars, as [[2]] is for bikes

[[any number]](例如:[[1]]、[[2]]时,我想使用正则表达式或任何其他方式将字符串拆分为字符串数组) 遇到。

[ 
[[1]],
" is for cars, as ",
[[2]],
" is for bikes"
]

What I have tried:

"[[1]] is for cars, as [[2]] is for bikes".split(/\[\[(\d+)\]\]/gi);

This returns ",1, is for cars, as ,2, is for bikes"

最佳答案

您的代码中有几个问题:

  1. .split在错误的地方使用捕获组,即您只捕获数字而不是 [[<digits>]]
  2. 由于在开始时也发现了拆分模式,因此您需要使用 .filter从结果数组中删除空字符串的方法。

const str = "[[1]] is for cars, as [[2]] is for bikes";
var arr = str.split(/(\[\[\d+\]\])/gi).filter(Boolean);
console.log(arr);
/*
[
"[[1]]",
" is for cars, as ",
"[[2]]",
" is for bikes"
]
*/

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

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