Search code examples
javascriptarraysreactjssplithighlight

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


I have an array(prop1) and also a set of keywords(prop2). I want to be able to split the array as per the keywords so that it looks like the wordSet array. How do I split this? The number of words in prop1 and prop2 can vary.

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

Solution

  • I'd construct a regular expression from the prop2s - make a RE that matches any characters until running into the keywords, and separately capture the matched keyword:

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