我创建了一个搜索机制,可以搜索字符串数组以查找完全匹配的字符串,但是我希望它更加直观。
我也可以在字符串中搜索字符串(例如chicken
中的grilled chicken
-但是问题是这允许用户键入ken
或{{1} },并返回ill
。
如果我输入grilled chicken
或chicken
,我希望它返回。
有人对如何建立更直观的搜索机制有任何建议吗?
编辑:
下面的正确答案在输入1个单词时有效,它将搜索字符串中的所有单个单词。但是,我意识到当您使用2个单词搜索时,它会失败(因为它仅分别搜索每个字符串单词)。
我通过在grilled
上添加|| search == string
来解决此问题,不仅包括单个单词匹配,还包括整个字符串匹配。
但是我仍然在搜索以下内容时遇到问题:
整个字符串匹配 要么 与单个单词匹配。
这意味着在if
和search = green cup
时失败。有没有办法通过减少要搜索的集合来解决此问题?也许类似于:
string = big green cup
但还要将string.split(' ')
也包含到数组中?
答案 0 :(得分:5)
尝试不使用正则表达式的最简单代码
var data = ["first string1 is here", "second string2 is here", "third string3 is here"];
var wordToSearch = "string2 is thanks";
var broken = wordToSearch.split(' ');
var result = 'not found';
if(broken.length == 1){
data.forEach(function(d){
d1 = d.split(' ');
if(d1.includes(wordToSearch))
result = d;
});
}
else if(broken.length == 2)
{
data.forEach(function(d){
var d1 = d.split(' ');
if(d1.includes(broken[0]) && d1.includes(broken[1]))
{
result = d;
}
});
}
alert(result);
答案 1 :(得分:1)
听起来您只想按整个单词搜索,如果是这样,您可以将字符串除以空格字符,然后在结果数组中搜索匹配项。
答案 2 :(得分:1)
我将RegExp与单词边界锚点-\b
一起使用。
function search(query, arr) {
var res = [];
var re = new RegExp('\\b' + query + '\\b');
arr.forEach(function (item) {
if (re.test(item)) res.push(item);
});
return res;
}