我的应用程序是一个文档查看器/阅读器。有一个搜索功能,用户在其中输入一个字符串,并返回结果列表。另外,查询的出现在页面上突出显示,以使其更加明显。搜索“类”,“样式”或其他也是html标签的词时,会发生该问题。替换html标签中的单词
content
只是喜欢这个网站的字符串:"<div class='classname' style='stylename'>Words that are eligible for highlighting</div>
突出显示的单词应该被替换:
query = 'class'
"<div class='classname' style='stylename'>Words that are eligible for highlighting are in here, including words like class and style</div>
当应用程序试图强调这些话,页面上的所有格式都会打破。这是我使用的突出显示搜索查询代码:
searchContent(content){
var searchQuery = SearchStore.getQuery()
if (searchQuery) {
var query = searchQuery.split(' ').map((q) => {
if (q.length > 2) {
return `\\b${q}\\b`;
}
}).join('|');
if (query.length > 0) {
//this is where the query is highlighted. It should not replace text inside <> tags
content = content.replace(new RegExp(query, 'gi'), (value) => {
return `<b style="background-color: yellow;">${value}</b>`;
});
}
}
return content;
}
有没有办法改写这一点,以便它时,它正在取代HTML标签内的文本,并阻止该网页打破检测?
这最终是一个可行的解决方案。在我的情况下,'content'是匹配的字符串,而不是'html'。谢谢。 –