0

We have a sentence as a string and an array of some of the phrases in the string like this:

const sentence = "I told her your majesty they are ready";
const phrases= ["your", "they are ready"];

I want to split the sentence string into array of arrays in which each array has been spliced based on phrases.

The desired result would be this:

[ ["I told her"], ["your"], ["majesty"], ["they are ready"] ]

We split the 'I told her' into one array because we want to have 'your' in an individual and separate array (because 'your' is one of the phrases elements).

I used a for loop to substring the sentence by iterating through the phrases with no luck.

Sara Ree
  • 3,417
  • 12
  • 48
  • Why do you want to have 2d array with the nested array always containing one string? Also is the trimming of strings intentional? – gurisko Oct 06 '20 at 15:07
  • I don't want a 2d array because I want to... I do want it because I need to :) Trimming of what... I don't understand? – Sara Ree Oct 06 '20 at 15:11
  • The ouput of your input should be `[ ["I told her "], ["your"], [" majesty "], ["they are ready"] ]` (notice spaces in the tokens) if you don't want to trim your chunks. That's why I am asking if trimming is intentional. – gurisko Oct 06 '20 at 15:13

1 Answers1

4

You could use a regular expression for this. When you use a capture group in it, it will be retained in the result of a .split() method call.

Your example shows that spaces are to be trimmed in the result, so you could use \s* for that in the regular expression.

Also, split("they are ready") would include a final empty string in the returned array. If you don't want such empty results to be included, then apply a filter on the result, like so:

const sentence = "I told her your majesty they are ready";
const phrases= ["your", "they are ready"];

// Build the regex dynamically:
const regex = RegExp("\\s*\\b(" + phrases.join("|") + ")\\b\\s*", "g");

let spliced = sentence.split(regex).filter(Boolean);

console.log(spliced);

NB: If your phrases contain characters that have a special meaning in a regex, then you should escape those characters.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • Nice! I tried with "I told her your majesty they are ready to go to your castle where they are ready to fight" and it all works perfectly. – Olivier Girardot Oct 06 '20 at 16:03