简体   繁体   中英

Safari RegEx lookbehind alternative

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}">$&</mark>`)
            });

Is there anyway to accomplish this without using negative lookbehind and negative lookahead in order for it to work also in Safari?

Use

let regex = new RegExp(
  `(<mark class="keyword_\\d">)?(?!\\B\\w)${this.escapeRegExp(keyword.value)}(?!</mark>)(?!\\w)`,
  'guim')
highlightedContent = highlightedContent.replace(regex, (match, gr1) => 
  gr1 ? match : `<mark class="keyword_${keyword.index}">${match}</mark>`)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM