JS實現搜索關鍵字匹配高亮顯示
首先看效果
需求:用戶輸入文字之後,調用後臺接口查詢匹配關鍵字(模糊搜索),並把匹配到的關鍵字進行高亮顯示。
實現思路:將拿到的數據進行拆分,例如:用戶輸入“羽毛球“,接口返回數據“{label:‘羽毛球手膠’}”,需要把羽毛球三個字高亮展示,首先我們將數據進行拆分,使用indexOf找到是否存在“羽毛球“字符串,找到關鍵字之後進行存儲,將帶有關鍵字的部分全部刪掉,繼續匹配,知道匹配結束。
代碼實現(代碼爲小程序代碼,其他語言思路一致):
matchingKeyFun() {
let keyword = this.data.keyword;
// 添加測試數據
let arr = [
{ label: '羽毛球關鍵字提示' },
{ label: '關鍵字搜索匹配羽毛球' },
{ label: '羽毛球搜索' },
{ label: '羽毛球拍測試羽毛球服測試羽毛球' }
];
// 最後輸出數組
let matchingKeys = [];
arr.forEach((item, index) => {
let f = true, label = item.label;
matchingKeys[index] = [];
while (f) {
// 找到當前位置
let position = label.indexOf(keyword);
if (position == -1) {
f = false;
// 未匹配到關鍵字
matchingKeys[index].push({ label: label.substring(0, label.length) })
} else {
// 匹配位置+關鍵字長度
let matchEnd = position + keyword.length;
// 非匹配中的關鍵字
matchingKeys[index].push({ label: label.substring(0, position) })
// 匹配中的關鍵字
matchingKeys[index].push({ label: label.substring(position, matchEnd), checked: true })
// 去掉匹配到文字,重新進行篩選
label = label.substring(matchEnd, label.length);
// 匹配到了末尾,不再繼續匹配
if (!label && label.length < 1) {
f = false;
}
}
}
})
this.setData({
matchingKeys: matchingKeys
})
},
頁面渲染
<view class="matching-key-block">
<view class="matching-item" wx:for="{{matchingKeys}}" wx:key="~this" wx:for-item="arr">
<view class="{{item.checked?'match-color':''}}" wx:for="{{arr}}" wx:key="~this">
{{item.label||''}}
</view>
</view>
</view>
css部分就不過多描述
公司項目碰到了這個需求,記錄一下,方便日後使用!