我想比较字符串和数组,以获取字符串中存在于数组中的单词或短语;但我不想包含字符串中未被空格包围的单词。
下面的代码比较了 userInput 和 myArray 并产生了这个结果:morning,good,good morning,go,he。 您会看到“go”和“he”也包括在内,尽管它们在 userInput 中不是单独的词(“go”来自“good”,“he”来自“hello”)。我研究了正则表达式,但不知道如何使用它们。我需要有关如何从结果中排除“go”和“he”的帮助。
const userInput = "hello good morning everyone";
const myArray = ["tomorrow", "morning", "good", "good morning", "go", "he"];
const intersect = myArray.filter(word =>
userInput.includes(word)
);
document.write(intersect);
您可以为
RegExp
中的每个phrase
实例化一个新的myArray
并在userInput
上执行它。
\b
)i
)来忽略大小写敏感const
userInput = "hello good morning everyone",
myArray = ["tomorrow", "morning", "good", "good morning", "go", "he"],
intersect = myArray.filter(phrase =>
new RegExp(`\\b${phrase}\\b`, 'i').exec(userInput));
console.log(intersect); // [ "morning", "good", "good morning" ]
您可以使用正则表达式对字符串和数组进行更精确的比较。以下代码将 userInput 字符串与 myArray 数组进行比较,并仅返回由空格字符分隔的单词:
const regex = /\b(?:myArray)\b/g;
const intersect = myArray.filter(word => userInput.match(regex));
document.write(intersect);
这将只返回单词“早上”、“好”、“早上好”,因为其他两个单词没有被空格字符包围。
举个例子
const userInput = "hello good morning everyone";
const myArray = ["tomorrow", "morning", "good", "good morning", "go", "he"];
const regex = /\b(?:myArray)\b/g;
const intersect = myArray.filter(word => userInput.match(regex));
document.write(intersect);
Regex非常强大,强烈推荐大家熟悉一下。使用像 regexr.com 这样的网站会有所帮助,因为你可以立即在那里测试东西。
\b
部分是单词边界(有两个\
因为需要转义)
const userInput = "hello good morning everyone";
const myArray = ["tomorrow", "morning", "good", "good morning", "go", "he"];
const intersect = myArray.filter(word => userInput.match(new RegExp("\\b" + word + "\\b")));
console.log(intersect);