'Search Exact String using custom pipe in Angular 8

I have created a custom pipe in order to filter my data. This is my pipe code

import { Pipe, PipeTransform } from '@angular/core';
  @Pipe({
  name: 'filterAll'
    })
  export class SpecialPipe implements PipeTransform {
    transform(value: any, searchText: any): any {
      if(!searchText) {
        return value;
      }
      return value.filter((data) => JSON.stringify(data).toLowerCase().includes(searchText) ); 
    }

  }

This filter is totally working well, but my requirement is to search the exact string. I have to return the values begins with my searchText (not included). I have also tried .startsWith(), which is also not working. Is there any way to achive this?



Solution 1:[1]

startsWith is what you're looking for.

Here's the working snippet:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter',
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], filterdata: string): any[] {
    if (!items) return [];
    if (!filterdata) return items;
    filterdata = filterdata.toString().toLowerCase();
    return items.filter((it) => {
      return it.name.toLowerCase().startsWith(filterdata);
    });
  }
}

Working StackBlitz demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Suresh Reddy