Search code examples
javascriptangularregexsearchangular-pipe

how to search highlight count occurences using angular pipes


I have below angular pipe code to search and highlight the text

Let's suppose pets.description has huge description text in below html file

 <div class="search-input">
     <label for="">Search here: </label> <input [(ngModel)]="searchText" type="search">
    </div>
    
    <div class="text-contaniner" [innerHtml]="text"  >
  </div>

and

export class AppComponent {
  searchText='';
  text=`somedummy text here`
}

style.css

   .highlight {
      background-color: violet;
      font-weight: bold;
    }

below is the actual pipe created

 transform(value: any, args: any): unknown {
      if(!args) return value;
      const re = new RegExp("\\b("+args+"\\b)", 'igm');
      value= value.replace(re, '<span class="highlighted-text">$&</span>');
      return value;
  }

This code searches the text and hihglights it.How do I also show the count occurrence of matches apart from highlighting the texts.


Solution

  • As per input from @Eliseo below transform function will help to get the count as well.

    transform(value: any, args: any): unknown {
      
      if(!args) return value;
      
      count = value.match(re).length;
      const re = new RegExp("\\b("+args+"\\b)", 'igm');
      value= value.replace(re, '<span class="highlighted-text">$&</span>');
      
      return {text:value,count:count};
    
    }