使用localStorage保存搜索记录

时间:2021-11-30 19:40:14
//过滤一个结果的空记录添加,过滤空搜索  默认保存10条记录,自己可修改
function setHistoryItems(keyword) {
keyword = keyword.replace("/^\s+|\s+$/g","");
let { historyIndexSearchItems } = localStorage;
if (historyIndexSearchItems === undefined) {
localStorage.historyIndexSearchItems = keyword;
} else {
const onlyItem = historyIndexSearchItems.split('|').filter(e => e != keyword);
if (onlyItem.length > 0){
historyIndexSearchItems = keyword + '|' + onlyItem.slice(0,9).join('|');
}
localStorage.historyIndexSearchItems = historyIndexSearchItems;
}
}
function clearHistory() {
localStorage.removeItem('historyIndexSearchItems');
}