比较一个字符串和一个数组,但是去掉没有被空格包围的单词

问题描述 投票:0回答:3

我想比较字符串和数组,以获取字符串中存在于数组中的单词或短语;但我不想包含字符串中未被空格包围的单词。

下面的代码比较了 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);
javascript html
3个回答
0
投票

您可以为

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" ]


0
投票

您可以使用正则表达式对字符串和数组进行更精确的比较。以下代码将 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);

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.