我想用sentences
数组的奇数和偶数索引填充两个数组(links
和sentence
):
这是我尝试未成功的尝试:
let link_sentence = ">60-1> don't you worry >6-2> I gonna make sure that >16-32> tomorrow is another great day"; //
let sentence = link_sentence.split(">")
let sentences= []
let links = []
for(let i = 0; i < sentence.length; i += 2) {
sentences.push(sentence[i]);
}
console.log(sentences)
预期输出应为:
//let links = ["60-1", "6-2", "16-32"];
//let sentences = ["don't you worry", "I gonna make sure that", "tommorow is another great day"];
最佳答案
您可以匹配部分,并省略分割的空字符串。
var link_sentence = ">60-1> don't you worry >6-2> I gonna make sure that >16-32> tomorrow is another great day",
sentences = [],
links = [];
link_sentence
.match(/\>[^>]+/g)
.reduce(
(r, s, i) => (r[i % 2].push(s.slice(1)), r),
[links, sentences]
);
console.log(sentences);
console.log(links);
.as-console-wrapper { max-height: 100% !important; top: 0; }