最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if string contains any keywords that exists in array - Stack Overflow

programmeradmin0浏览0评论

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.

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. Currently includes() returns false because it's trying to match the exact string.

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.

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. Currently includes() returns false because it's trying to match the exact string.

Share Improve this question edited Dec 31, 2017 at 14:46 Estus Flask 224k79 gold badges472 silver badges612 bronze badges asked Dec 31, 2017 at 14:24 pabloBarpabloBar 3173 silver badges13 bronze badges 1
  • Use a regular expression on the string. – Rob Monhemius Commented Dec 31, 2017 at 14:33
Add a ment  | 

1 Answer 1

Reset to default 7

You need to check each word in filters against each content.name. You can do that with .some() which will return true (and halt the search early) when a match is found.

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

Note that .includes() will match subsections of words. 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.

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.

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))
发布评论

评论列表(0)

  1. 暂无评论