我们有一个字符串形式的句子和字符串中一些短语的数组,如下所示:
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循环通过遍历短语来子串句子,但没有成功。
发布于 2020-10-06 23:10:56
为此,您可以使用正则表达式。当您在其中使用捕获组时,它将保留在.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);
注意:如果您的短语包含在正则表达式中具有特殊含义的字符,那么您应该escape这些字符。
https://stackoverflow.com/questions/64228485
复制相似问题