Search code examples
javascripthighlightfind-occurrences

Get all the occurrences with window.find


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


Solution

  • 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