【发布时间】:2020-09-03 13:00:30
【问题描述】:
我正在构建一个自定义搜索,截至目前,如果我输入“The R”,我会首先获得 The Fellowship of the Ring 的结果列表,因为它的 .text 中包含短语“the ring”。我希望王者归来是第一。有没有一种方法可以让 .name 字段更具相关性或根据名称 .field 和输入文本对匹配数组进行排序?
HTML
<section class="container-fluid px-0 justify-content-center">
<div class="row no-gutters">
<div class="col d-flex justify-content-center search">
<form class="form-inline position-relative">
<input id="search" class="form-control form-control-search" type="text" placeholder="Search..." aria-label="Search">
</form>
<div id="match-list" class="d-none"></div>
</div>
</div>
</section>
JAVASCRIPT
const searchIndex = async searchText => {
const res = await fetch('/data/index.json');
const index = await res.json();
matchList.classList.remove("d-none");
// Get matches to current text input
let matches = index.filter(index => {
const regex = new RegExp(`${searchText}`, 'gi');
return index.name.match(regex) || index.text.match(regex);
});
// Clear when input or matches are empty
if (searchText.length === 0) {
clearSearch();
}
outputHtml(matches);
};
function clearSearch(){
matches = [];
matchList.classList.add("d-none");
}
// Show results in HTML
const outputHtml = matches => {
if (matches.length > 0) {
const html = matches.map(function(match){
return `<a href="${match.url}">
<div class="media mb-2">
<div class="component-icon-slot my-auto" style="background-image: url('/img/${match.url}/icon.png"></div>
<div class="media-body pl-2">
<h3 class="mt-0 mb-0">${match.name}</h3>
<b>${match.type}</b><br/>
<i>Found in <b>${match.product}</b></i><br/>
${match.text}
</div>
</div></a>`
}
}).join('');
matchList.innerHTML = html;
}
};
index.JSON
[
{
"name": "The Fellowship of the Rings",
"type": "book",
"text": "Bilbo reveals that he intends to leave the Shire for one last adventure, and he leaves his inheritance, including the Ring, to his nephew Frodo. Gandalf investigates...",
"url": "books/the-fellowship-of-the-rings",
"product": "Books"
},
{
"name": "The Two Towers",
"type": "book",
"text": "Awakening from a dream of Gandalf fighting the Balrog in Moria, Frodo Baggins and Samwise Gamgee find themselves lost in the Emyn Muil near Mordor and discover they are being tracked by Gollum, a former bearer of the One Ring.",
"url": "books/the-two-towers",
"product": "Books"
},
{
"name": "The Return of the King",
"type": "book",
"text": "Gandalf flies in with eagles to rescue the Hobbits, who awaken in Minas Tirith and are reunited with the surviving Fellowship.",
"url": "books/the-return-of-the-king",
"product": "Books"
}
]
【问题讨论】:
-
这个问题没有明确的答案。您可以采用不同的策略来评估相关性。
-
无论优先考虑名称然后是文本的解决方案,我都可以。
-
按匹配/不匹配对您来说是否足够,或者您需要更花哨的东西?
-
我正在尝试按相关性对它们进行排序,因此,首先是名称,然后是文本。或者,我也尝试从字符串的开头进行搜索,我使用了 RegExp(
^${searchText}, 'gi');但如果我只写“国王”,我将不会得到任何结果。 -
你不应该只使用这样的正则表达式,因为正则表达式使用特殊字符。相反,比较
string.toLowerCase().includes(searchText.toLowerCase())。
标签: javascript arrays json sorting search