gpt4 book ai didi

javascript - 从输入中创建排除过滤器

转载 作者:行者123 更新时间:2023-12-03 04:05:11 24 4
gpt4 key购买 nike

我正在尝试创建一个搜索字符串来识别搜索中的字符。

如果文本包含-,我想像排除一样使用它。

只有当-字符前面有一个空格或者位于位置0时才应排除。

搜索 foo -bar 它应该只在 foo 存在但 bar 不存在的地方。

我在 CodeSandbox 上创建了一个示例:https://codesandbox.io/s/ZvAqXoOQ

代码应该像这样工作,但要识别何时应用 every(e => !title.

foo

.filter(movie => {
const title = movie.title.toLowerCase();
return search.every(e => title.includes(e.toLowerCase()));

.filter(movie => {
const title = movie.title.toLowerCase();
return search.every(e => !title.includes(e.toLowerCase()));
});

最佳答案

根据术语的第一个字母选择条件。像这样的东西。

const movies = ['foo', 'foo bar', 'baz', 'qux', 'foo baz'].map(title => ({title}))

const search = 'foo -bar'.split(' ')


console.log(
movies.filter(
({title}) => search.every(term => term[0] === '-' ? !title.includes(term.substring(1)) : title.includes(term))
)
)

const movies = ['foo', 'foo bar', 'baz', 'qux', 'foo baz'].map(title => ({title}))

const search = 'foo -'.split(' ')


console.log(
movies.filter(
({title}) => search.every(term => {
if(term === '-') return true

if(term[0] === '-') return !title.includes(term.substring(1))

return title.includes(term)

})
)
)

关于javascript - 从输入中创建排除过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44591522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com