我正在构建一个搜索自动建议组件,其中结果使用 hyperHTML 呈现。从服务器返回的建议的匹配字符串部分应突出显示。
我正在使用正则表达式并String.prototype.replace
突出显示匹配的部分,但不知何故我无法将它的返回值输出到 HTML。它只是将标签呈现<strong>
为字符串。
我尝试了很多不同的方法来解决这个问题,但没有任何成功并且我的想法已经用完了......
这是我的渲染功能:
const suggestionsContainer = document.querySelector(
".js-suggestions-container"
);
const suggestions = [{
title: "lorem ipsum dolor sit amet",
url: "#"
},
{
title: "lorem ipsum dolor sit amet",
url: "#"
}
];
let query = "ipsum";
function renderSuggestions(suggestions, query) {
const queryRegEx = new RegExp(query, "gi");
hyperHTML.bind(suggestionsContainer)`
${suggestions.map((suggestion) => hyperHTML.wire(suggestion)`
<a href="${suggestion.url}">
${hyperHTML.wire()`${suggestion.title.replace(queryRegEx, "<strong>$&</strong>")}`}
</a>
`)}
`;
}
renderSuggestions(suggestions, query);
a {
display: block;
margin: 1rem 0;
}
<script src="https://unpkg.com/hyperhtml@latest/min.js"></script>
<div class="js-suggestions-container"></div>