0

I want to highlight in a text all the occurrences from a word that I have in my URL. For the first occurrence everything works fine. But I don't know how to go to the next one.

highlightText: function(urlParams) {
  var urlSearch = window.location.search;
  var urlParams = new URLSearchParams(urlSearch);
  var searchText = urlParams.get('search');
  if (window.find(searchText)) {
    var el = document.getElementById('collection-content');
    text = el.innerHTML;
    marked = text.replace(searchText, "<mark>" + searchText + "</mark>");
    el.innerHTML = marked;
  }
}

I have tried to add a while(window.find(searchText) before the if but it doesn't work, it seems to loop only on the first occurence of my word.

Thanks in advance

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • 3
    Obligatory warning: `window.find` is [non-standard](https://developer.mozilla.org/en-US/docs/Web/API/Window/find), use at your own risk. Additionally it's the wrong tool for this, as it returns a *boolean*. – Jared Smith Sep 21 '20 at 12:52
  • Can you provide a codesandbox.io that replicates it? – Tasos Sep 21 '20 at 12:52
  • Why would you want to do this? – Liam Sep 21 '20 at 12:52
  • @Liam highlight every instance of a specific word on a page? Doesn't sound unreasonable.... – Jared Smith Sep 21 '20 at 12:53
  • 2
    @Jared: it sounds reasonable, but it does seem to be reinventing the wheel of "ctrl + F". That's not necessarily bad, and could be a good learning experience, but it seems a little redundant, especially when - as you already mentioned - the wrong tool is being used. – David Thomas Sep 21 '20 at 12:55
  • 1
    It sounds like an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). If you own the web page why not just change the markup before it renders? – Liam Sep 21 '20 at 12:55
  • @DavidsaysreinstateMonica fair – Jared Smith Sep 21 '20 at 12:55
  • @Liam Actually in the site I searched for a word, then i have an overview of all the documents that contains this word. When i open one document, i insert the searched word in my url so that i can spread my research to the content of the document and highlight where are the searched words. – Valentin Gonzalez Sep 21 '20 at 13:02

1 Answers1

1

If you're not using regex then it'll only replace the first occurrence, you might try this, Also modify the regex as per your needs.

highlightText: function(urlParams) {
  var urlSearch = window.location.search;
  var urlParams = new URLSearchParams(urlSearch);
  var searchText = urlParams.get('search');
  if (window.find(searchText)) {
    var el = document.getElementById('collection-content');
    text = el.innerHTML;
    marked = text.replace(
      RegExp(`(${searchText})`),
      "<mark>" + searchText + " </mark>");
    el.innerHTML = marked;
  }
}

Note: The match is case sensitive

Sudhanshu Kumar
  • 1,926
  • 1
  • 9
  • 21