如何在搜索结果中正确高亮searchInput输入的匹配内容
问题根因
你的代码存在几处核心问题:
- 最直接的错误是取错了搜索关键词的值:
this.search是你获取到的输入框DOM元素对象,不是用户输入的文本内容。当你把DOM对象直接传入new RegExp()时,JS会自动将对象转为字符串[object HTMLInputElement],你的正则实际在匹配这个字符串里的所有字符,所以不管你输入什么搜索词,都会高亮c、m、l这类存在于[object HTMLInputElement]中的字符,和你输入的内容完全无关。 - 缺少正则特殊字符转义逻辑:如果用户输入
.+*?这类正则语法里的特殊字符,会导致正则匹配逻辑异常,甚至出现报错。 - 目前的正则默认只匹配第一个命中的内容,如果搜索词在公司名/代码里出现多次,只会高亮第一个结果。
修复代码
完整修复后的代码如下:
class SearchResults { constructor(element) { this.element = element; this.search = document.getElementById("searchInput"); } // 新增:正则特殊字符转义方法 #escapeRegExp(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } renderResults(companyProfiles) { // 修复:正确获取输入框的文本值,空格过滤 const searchKeyword = this.search.value.trim(); // 提前构造可复用的高亮正则,i表示忽略大小写,g表示全局匹配所有命中项 const highlightReg = searchKeyword ? new RegExp(this.#escapeRegExp(searchKeyword), 'ig') : null; let dataList = ""; companyProfiles.forEach((company) => { const { profile } = company; // 涨跌幅样式处理 const profileChangesPercent = Number(profile.changesPercentage); let changesPercentage; if (profileChangesPercent >= 0) { changesPercentage = `<span style="color: green;"> ${profileChangesPercent.toFixed(2)}%</span>`; } else if (profileChangesPercent < 0) { changesPercentage = `<span style="color: red;"> ${profileChangesPercent.toFixed(2)}%</span>`; } else { changesPercentage = ""; } // 公司名高亮处理 let companyName = profile.companyName; if (highlightReg) { companyName = companyName.replace(highlightReg, match => `<strong style="background: yellow;">${match}</strong>`); } // 公司代码高亮处理 let symbol = company.symbol; if (highlightReg) { symbol = symbol.replace(highlightReg, match => `<strong style="background: yellow;">${match}</strong>`); } // 列表拼接,注意跳转参数用的是原始的company.symbol,不要用修改后的带标签的symbol dataList += `<li onclick="location.href='./html/company.html?symbol=${company.symbol}'"> <span><img src='${profile.image}' width="30px" height="30px" onerror="this.src='./images/MonkeyPlaceholder.png'" alt="monkey"/> <p>${companyName}</p></span> <span><span style="font-weight:bold">${symbol}</span> <span>${changesPercentage}</span><span><button class="comparebutton">Compare</button></span></span></li>`; }); this.element.innerHTML = `<ul>${dataList}</ul>`; } }
错误效果复现
你遇到的乱高亮效果如下图:
内容的提问来源于stack exchange,提问作者Barak David
相关产品推荐
相关产品推荐

