简体   繁体   English

检查字符串是否包含数组中存在的任何关键字

[英]Check if string contains any keywords that exists in array

I am trying to filter some content based on which keyword exists in an array, but not sure how to do that, tried using includes , indexof , and search functions, but it didn't work in my case. 我试图根据数组中存在哪个关键字来过滤一些内容,但不知道如何做到这一点,尝试使用includesindexofsearch功能,但它在我的情况下不起作用。

My first attempt: 我的第一次尝试:

const filters = ['movie', 'food']
contents
 .filter( content => filters.includes(content.name))

the problem is that content.name is a string with multiple words eg "watch your favourite movie", "vote for your favourite food", etc. and I want to check if a string includes one of the keywords in filters variable. 问题是content.name是一个包含多个单词的字符串,例如“看你最喜欢的电影”,“投票给你最喜欢的食物”等等。我想检查一个字符串是否包含过滤器变量中的一个关键字。 Currently includes() returns false because it's trying to match the exact string. 目前includes()返回false因为它试图匹配确切的字符串。

You need to check each word in filters against each content.name . 您需要针对每个content.name检查filters中的每个单词。 You can do that with .some() which will return true (and halt the search early) when a match is found. 您可以使用.some()执行此操作,当找到匹配项时,它将返回true (并提前停止搜索)。

const filters = ['movie', 'food']
const result = contents.filter(content => 
  filters.some(s => content.name.includes(s))
)

Note that .includes() will match subsections of words. 请注意, .includes()将匹配单词的子部分。 You need to establish word boundaries, perhaps with a regex, to get a whole word match. 您需要建立单词边界,可能使用正则表达式,以获得完整的单词匹配。

You can do this by creating an array of regexes instead of strings, and using the .test() method of the regex. 您可以通过创建正则表达式数组而不是字符串,并使用正则表达式的.test()方法来完成此操作。

const filters = [/\bmovie\b/, /\bfood\b/]
const result = contents.filter(content => 
  filters.some(re => re.test(content.name))
)

Add the i modifier to each regex if it should be a case insensitive match. 如果它应该是不区分大小写的匹配,则将i修饰符添加到每个正则表达式。

Or instead of an array of regex, you can use a single regex. 或者代替正则表达式数组,您可以使用单个正则表达式。

const filters = /\b(?:movie|food)\b/
const result = contents.filter(content => filters.test(content.name))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM