Sundeep
Sundeep

Reputation: 179

Data Should be Filter with the starting Letter

I need to Filter the data by using Starting Letter, But here the data is getting filter with starting and Middle of the letters also. for example: Karnataka is the word I need to filter, But If I search with middle letters like "rna" it gets filter, but in my case I need to get filter by starting letter "K" only..

<div class="container">
  <input type ="text" [(ngModel)] ="param"/>  
 </div>

set param(names){
   this.value =names ? this.gettingDatafromServer.filter(item =>item.address.toLowerCase().indexOf(names.toLowerCase())!==-1) : this.gettingDatafromServer
 
}

Upvotes: 0

Views: 68

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50759

This is happening because .indexOf() will search the entire string, not just the start. You can instead use the .startsWith() method for your filter() callback:

item => item.address.toLowerCase().startsWith(names.toLowerCase())

If you need better browser support, you can polyfill it.

Upvotes: 1

Related Questions