我正在尝试创建一个搜索框,用户在其中键入搜索查询,然后下拉菜单开始显示匹配结果。我正在尝试下面的函数,该函数的确基于quoteCategory,quoteText或quoteAuthorName返回匹配的值。问题是,仅当查询在具有精确词的对象数组中匹配时才返回对象,例如,如果用户键入LOVE,它将匹配并在下拉列表中显示结果,但是当用户键入LOVE任何其他字符时,它不返回显示任何结果。
我要实现的目标是,如果有任何单词与对象数组中的用户查询匹配,它将返回结果。基本上匹配应基于部分字符串或子字符串。
import React from 'react'
export const GlobalSearch = () => {
const [textQuote, setTextQuote] = useContext({
{
userId: '123',
quoteAuthorName: 'Any Two',
quoteCategory: 'Motivational',
quoteType: 'textQuote',
quoteText: 'If there’s no',
},
{
userId: '124',
quoteAuthorName: 'Any One',
quoteCategory: 'Love',
quoteType: 'textQuote',
quoteText: 'If there’s no market, then it may not be one',
}
)
const [searchTerm, setSearchTerm] = useState("");
let resultsObj = textQuote.filter(quote =>
quote.quoteCategory.toLowerCase().includes(searchTerm.toLowerCase())
|| quote.quoteAuthorName.toLowerCase().includes(searchTerm.toLowerCase())
|| quote.quoteText.toLowerCase().includes(searchTerm.toLowerCase())
);
}
您可以在正则表达式中转换字符串。使用香草Javascript的示例:
textQuote = [
{
userId: '123',
quoteAuthorName: 'Any Two',
quoteCategory: 'Motivational',
quoteType: 'textQuote',
quoteText: 'If there’s no',
},
{
userId: '124',
quoteAuthorName: 'Any One',
quoteCategory: 'Love',
quoteType: 'textQuote',
quoteText: 'If there’s no market, then it may not be one',
}
];
let searchTerm = "love is blind";
let searchArray = searchTerm.trim().split(" ");
let re = new RegExp(searchArray.join("|"), "i");
let resultsObj = textQuote.filter(quote =>
re.test(quote.quoteCategory) ||
re.test(quote.quoteAuthorName) ||
re.test(quote.quoteText)
);
document.write(JSON.stringify(resultsObj));
输出:
[{"userId":"124","quoteAuthorName":"Any One","quoteCategory":"Love","quoteType":"textQuote","quoteText":"If there’s no market, then it may not be one"}]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句