Akshay
Akshay

Reputation: 391

Angular 4 case insensitive search result with pipe

Hello I am creating a search pipe in angular4 which filter company name from Json Data. The search filter is working but is case sensitive, how I can I ignore case sensitivity from my search filter. I am putting only the code which is related to the subject.

My Pipe code -

import { Pipe, PipeTransform } from '@angular/core';
import { JobsService } from '../services/jobs.service';

@Pipe({
    name: 'filter',
    pure: false
})
export class FilterPipe implements PipeTransform {
transform(items: any[], term): any {
    console.log('term', term);

    return term 
        ? items.filter(item => item.company.indexOf(term) != -1)
        : items;
    }
}

Search Box -

<input type="text" [(ngModel)]="term" name="term">

Data -

<div *ngFor="let joblist of jobList | filter: term">
    {{joblist.company}}
</div>

Upvotes: 1

Views: 2036

Answers (2)

amal
amal

Reputation: 3170

You can use the String.protoype.search() method instead of the indexOf() method for checking against a case insensitive regular expression.

So your return statement could look like this:

return term 
 ? items.filter(item => item.company.search(new RegExp(term, 'i')) !== -1)
 : items;

If you have special characters like \ in your terms variable, then you need to account for that as well in your filter. The above method should work for a normal alphanumeric terms variable.

The i in new RegExp(term, 'i') accounts for case-insensitive terms pattern.

The above code will let in any company values which has the term anywhere in it. If you want a more stricter check, you can replace the RegExp constructor with this: new RegExp('^' + terms + '$', 'i') in the above code snippet. These characters, ^ & $ specify the 'start' and 'end' of a regex pattern respectively.

More on search and regexp.

Upvotes: 1

Aman Jain
Aman Jain

Reputation: 2582

You should filter term value as:

...term.toLowerCase().company...

Upvotes: 1

Related Questions