我们有一个字符串形式的句子和字符串中一些短语的数组,如下所示:
const sentence = "I told her your majesty they are ready";
const phrases= ["your", "they are ready"];
我想将sentence
字符串拆分为数组数组,其中每个数组都是基于phrases
拼接的。
期望的结果是:
[ ["I told her"], ["your"], ["majesty"], ["they are ready"] ]
我们将"我告诉过她"拆分为一个数组,因为我们希望将"你的"放在一个单独的数组中(因为"你"是短语元素之一(。
我用了一个for循环,通过遍历短语来减少句子的子串,但没有运气。
您可以使用正则表达式。当您在其中使用捕获组时,它将保留在.split()
方法调用的结果中。
您的示例显示了要在结果中修剪空格,因此可以在正则表达式中使用s*
。
此外,split("they are ready")
将在返回的数组中包括最后一个空字符串。如果你不想包含这样的空结果,那么在结果上应用filter
,比如:
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);
注意:如果你的短语包含正则表达式中有特殊含义的字符,那么你应该转义这些字符。