I'm implementing a search highlight feature. I've been able to use regex to find all instances of a particular keyword in my table, and highlight it. What I'm trying to do now is be able to jump to the next/prev highlight word using Enter and Shift+Enter resp. Here's what I'm currently doing:
highlightSearchKeyword () {
const reviews = document.querySelectorAll('span[data-v-071a96ec=""]')
const formattedKeyword = this.searchKeyWord.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
let count = 0
reviews.forEach(rev => {
const substring = new RegExp(formattedKeyword, 'gi')
let description = rev.innerText
if (formattedKeyword !== '') {
try {
count += description.match(substring || []).length
} catch (error) {
count += 0
}
}
description = description.replace(substring, match => `<span class="highlight" id="search-${some-id}">${match}</span>`)
rev.innerHTML = description
})
this.highlightedWordCount = count
}
As you can see, I'm replacing each match with a string that surrounds the original match word by a <span>
tag. I want to give each instance of a match an id, so that I can do something like:
const elem = document.querySelector(`#search-{some-id}`)
elem.scrollIntoView()
If someone could help me out with this that'd be great.