题解 | #智能提示#
智能提示
http://www.nowcoder.com/practice/efccf73b4ceb4446b6d71127f874e6d3
思路
动态生成正则表达式
由于下面的转义之后前面会带\
所以这里要连\
一起捕获
const re = new RegExp( value .replace(/(\\.)/g, "$1.*?") )
用正则表达式去过滤结果
这里题目故意挖了个坑,正则表达式的符号要转义
replace(/([\\\/\(\)\+\*\?\:\\[\]\^\$])/g, "\\$1")
完整代码如下
function listSuggests(value) { if (!value) return []; const re = new RegExp( value .replace(/([\\\/\(\)\+\*\?\:\\[\]\^\$])/g, "\\$1") .replace(/(\\.)/g, "$1.*?") ); const items = window.items; const result = items.filter((i) => re.test(i)); return result; } function onInput(evt) { const suggests = listSuggests(evt.currentTarget.value.trim()); const s = document.getElementsByClassName("js-suggest")[0]; const ul = s.children[0]; ul.innerHTML = ""; if (!suggests.length) return s.classList.add("hide"); s.classList.remove("hide"); ul.innerHTML = suggests.map((i) => `<li>${i}</li>`).join(""); } function suggest(items) { window.items = items; const el = document.getElementsByClassName("js-input")[0]; // el.addEventListener("change", onInput); el.addEventListener("input", onInput); onInput({ currentTarget: el }); }