如何根据关键字动态拆分数组?

How to split an array dynamically on the basis of keywords?

我有一个数组(prop1) 和一组关键字(prop2)。我希望能够根据关键字拆分数组,使其看起来像 wordSet 数组。我该如何拆分? prop1 和 prop2 中的字数可以变化。

prop1 = {"Hello  World. I want to welcome you to my kingdom"}
prop2 = ['World', 'welcome', 'kingdom']


const wordSet = 
[
  "Hello ",
  "World",
  ". I want to ",
  "welcome",
  " you to my ",
  "kingdom"
]

arr.map((wordSet) => {
  const isHighlighted = prop2.indexOf(wordSet) > -1;
  return <span className={isHighlighted ? classes.highlighted : classes.other}>{wordSet}</span>
})

我将使用拆分进行多次传递。我不确定它是否会成功,但让我试一试!

var str = "Hello  World. I want to welcome you to my kingdom";
var arr = ['World', 'welcome', 'kingdom'];
var final = [str];

for (var i = 0; i < arr.length; i++) {
  final = final.flat(2).map(function (f) {
    return f.split(arr[i]).join("aaaa" + arr[i] + "aaaa").split("aaaa");
  }).flat(2).filter(a => a);
}

console.log(final);

aaaa 可能是单词或数组的一部分,这是我在这里得到的唯一警告。但是我们可以使用这样的方式切换它:

var str = "Hello  World. I want to welcome you to my kingdom";
var arr = ['World', 'welcome', 'kingdom'];
var final = [str];

for (var i = 0; i < arr.length; i++) {
  final = final.flat(2).map(function (f) {
    // Not fool proof.
    var sep = str.indexOf("aaaa") > -1 ? "bbbb" : "aaaa";
    return f.split(arr[i]).join(sep + arr[i] + sep).split(sep);
  }).flat(2).filter(a => a);
}

console.log(final);

我会从 prop2 构造一个正则表达式 - 制作一个 RE 匹配任何字符直到 运行 进入关键字,并单独捕获匹配的关键字:

const prop1 = "Hello  World. I want to welcome you to my kingdom";
const prop2 = ['World', 'welcome', 'kingdom'];
const pattern = new RegExp('(.*?)($|' + prop2.join('|') + ')', 'gi');
const wordSet = [...prop1.matchAll(pattern)]
  .flatMap(m => [m[1], m[2]])
  .filter(Boolean);
console.log(wordSet);