0

I'm trying to implement a highlight function, that wraps all words within an article that matches users search, with an <span class="highlight"></span> element. However, with that code, all elements within an article are going to be replaced with "<span class='highlight'>" + str + "</span>" that includes elements such as <a href=""></a> and <img /\>, which causes them eventually to break.

The goal is to highlight the matching words that the user is searching for within the headings, paragraphs and spans. Image and Link elements should remain as they are. Is there a way to exclude certain HTML elements from that RegExp? Code:

const search = query.get("search");

{search
  ? parse(
      article.data.content.replace(
        new RegExp(search, "gi"),
        (str) => {
          return (
            "<span class='highlight'>" + str + "</span>"
          );
        }
      )
    )
  : parse(article.data.content)}
Tony Caterev
  • 127
  • 1
  • 2
  • 13
  • 1
    Please see https://stackoverflow.com/a/1732454/3412322. Then see https://stackoverflow.com/a/6520267/3412322. – Daniel Beck Jan 17 '23 at 01:00
  • 2
    Here is an interesting alternative to regex that adds highlights over the search phrase but without changing the innerHTML. See: [How to highlight search text from string of html content without breaking](https://stackoverflow.com/a/58721469/943435) – Yogi Jan 17 '23 at 01:07

0 Answers0