简体   繁体   English

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

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

I have an array(prop1) and also a set of keywords(prop2).我有一个数组(prop1)和一组关键字(prop2)。 I want to be able to split the array as per the keywords so that it looks like the wordSet array.我希望能够根据关键字拆分数组,使其看起来像 wordSet 数组。 How do I split this?我如何拆分这个? The number of words in prop1 and prop2 can vary. 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>
})

I'll do multi pass using split.我将使用拆分进行多遍。 I am not sure if it will work out well, but let me give a try!我不确定它是否会奏效,但让我试一试!

 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);

There could be possibly the aaaa might be a part of the word or the array, that's the only caveat I have got here.可能aaaa可能是单词或数组的一部分,这是我在这里得到的唯一警告。 But we can switch it using something like this:但是我们可以使用这样的东西来切换它:

 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);

I'd construct a regular expression from the prop2 s - make a RE that matches any characters until running into the keywords, and separately capture the matched keyword:我会从prop2 s 构建一个正则表达式 - 制作一个匹配任何字符的 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM