As I develop my web page, I encountered an issue while trying to highlight text based on user input in the search box. My search algorithm matches each space-separated keyword, but ran into problems when including brackets in the search term. This caused a SyntaxError: Invalid regular expression due to unterminated groups being interpreted by the regex. Despite attempts to escape the brackets and other characters, the highlighting feature stopped functioning properly.
Visit this link for more information
highlight (str) {
// The line below works, but it doesn't allow highlighting multiple disconnected keywords
// var replacedStr = (this.search || '').replace(/[-[\]{}()*+!<=:?.\\^$|#\s,]/g, '\\$&')
// you can comment this line and uncomment above to see a different but not perfect option
var replacedStr = (this.search || '').replace(/ /g, '|')
return str.replace(new RegExp(replacedStr, 'gi'), match => {
return '<span class="font-weight-bold">' + match + '</span>'
})
}
I attempted to escape the brackets as shown in the commented line, but it resulted in the function failing to properly highlight all keywords within the text :/
Any suggestions or ideas to address this issue?