When I try to search for the title of a product, it only shows results if it is either the exact words, one word, or a combination of consecutive words.
For example, if I'm trying to find the product blue flying car
, the product does not show if I try searching for blue car
. Basically I want my search to be fixed to accept different combinations. How can I do this?
var item_xlsx = './assets/data/products.xlsx';
var all_items = [];
var all_cats = [];
var subcats = [];
var catQuery = '';
var subCatQuery = '';
var titleQuery = '';
function load_data() {
// get query parameters
catQuery = get_param('cat');
subCatQuery = get_param('subcat');
titleQuery = get_param('searchtext');
$('#searchtext').val(titleQuery);
$('#cat').val(catQuery);
fetch(item_xlsx).then(function (res) {
if (!res.ok) throw new Error("fetch failed");
return res.arrayBuffer();
}).then(function (ab) {
var data = new Uint8Array(ab);
var workbook = XLSX.read(data, { type: "array" });
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name];
all_items = XLSX.utils.sheet_to_json(worksheet, { raw: true });
populate_cats();
populate_subcats(catQuery);
render_category_form();
render_search_form(catQuery, titleQuery, all_items);
render_search_summary(catQuery, titleQuery, all_items);
render_search_results(catQuery, titleQuery, all_items);
});
}
function get_param(name) {
name = name.replace(/[[]/, '\[').replace(/[]]/, '\]');
var regex = new RegExp('[\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/+/g, ' '));
}
/* Filter items and render search results */
function render_search_results(cat, query, items) {
let results = all_items.filter(function (value, index, self) { // filter by cat
if (!catQuery || catQuery === "") {
return true;
} else {
return value.cat == catQuery;
}
}).filter(function (value, index, self) { // filter by subcat
if (!subCatQuery || subCatQuery === "") {
return true;
} else {
return value.subcat == subCatQuery;
}
}).filter(function (value, index, self) { // filter by query
if (!titleQuery || titleQuery === "") {
return true;
} else {
var regex = new RegExp(titleQuery, "i");
return value.name.search(regex) != -1 || value.audience.search(regex) != -1;
}
})
question from:
https://stackoverflow.com/questions/65894487/how-to-change-search-function-to-accept-any-combination-of-words 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…