Safari Regex LookBehind替代方案
我希望能够突出显示HTML字符串中的关键字,
我有一个关键字数组,该数组可以包含关键字,例如存储框
厨房存储框
厨房组织者
。 还有一个内容,我需要突出显示这些关键字。
如您所见,储存框以2个关键字重复,我不想突出显示存储框
如果厨房存储框
已经突出显示。因此,首先,我订购了最大长度的关键字,因此我首先要突出显示较大的关键字,然后突出显示较大的内容。
我正在使用以下代码将每个找到的关键字替换为< mark> {keyword}</mark>
_.each(this.keywords, keyword => {
keyword.value = this.replaceNbsps(keyword.value)
// find the keyword but do not take already highlighted elements into consideration
// for this we use negative lookbehind and negative lookahead to not include keywords that are preceded with <mark> and succeeded with </mark>
let regex = new RegExp(`((?<=\\s|^|\\W)(?<!<mark class="keyword_\\d">)${this.escapeRegExp(keyword.value)}(?!<\/mark>)(?=\\s|$|\\W))`, 'guim')
highlightedContent = highlightedContent.replace(regex, `<mark class="keyword_${keyword.index}">$&</mark>`)
});
无论如何都可以实现此目的还在野生动物园中吗?
I want to be able to highlight keywords inside an HTML string
I have a keywords array that can contain keywords like storage box
kitchen storage box
kitchen organiser
.
Also there is a content where i need to highlight these keywords.
As you can see the storage box is repeated in 2 keywords and i don't want to highlight storage box
if kitchen storage box
is already highlighted. So first, i ordered the keywords by max length so i get to highlight the bigger ones first and then the smaller ones.
I am using the following code to replace each found keyword with <mark>{keyword}</mark>
_.each(this.keywords, keyword => {
keyword.value = this.replaceNbsps(keyword.value)
// find the keyword but do not take already highlighted elements into consideration
// for this we use negative lookbehind and negative lookahead to not include keywords that are preceded with <mark> and succeeded with </mark>
let regex = new RegExp(`((?<=\\s|^|\\W)(?<!<mark class="keyword_\\d">)${this.escapeRegExp(keyword.value)}(?!<\/mark>)(?=\\s|$|\\W))`, 'guim')
highlightedContent = highlightedContent.replace(regex, `<mark class="keyword_${keyword.index}">amp;</mark>`)
});
Is there anyway to accomplish this without using negative lookbehind and negative lookahead in order for it to work also in Safari?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
Use