admin管理员组文章数量:1430093
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.
- Use a regular expression on the string. – Rob Monhemius Commented Dec 31, 2017 at 14:33
1 Answer
Reset to default 7You 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))
本文标签: javascriptCheck if string contains any keywords that exists in arrayStack Overflow
版权声明:本文标题:javascript - Check if string contains any keywords that exists in array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745507200a2661299.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论