1

I want to search pokemon and find all Pokémon results (with accent)

My array:

let games = ['The Legend of Zelda', 'Pokémon', 'Chrono Trigger']

How I'm doing:

HTML

<input type="text" [(ngModel)]="search">
<ul>
  <li *ngFor="let game of games | filterBy:[]:search">{{game}}</li>
</ul>

I'm using the ng-pipes package to use filterBy

TS

public search: string = ''

But if I type pokemon he don't match with Pokémon

2 Answers2

1

Thanks everyone, I managed to solve by doing some tests. I decided to create a function that returns the value handled by regex.

Follow the result

TS

public games = ['The Legend of Zelda', 'Pokémon', 'Chrono Trigger']
public gamesCopy = this.games

public search: string = ''

private slug(val) {
  val = val.replace(/[áàãâä]/g, 'a')
  val = val.replace(/[ÁÀÃÂÄ]/g, 'a')
  val = val.replace(/[éèêë]/g, 'e')
  val = val.replace(/[ÉÈÊË]/g, 'e')
  val = val.replace(/[íìîï]/g, 'i')
  val = val.replace(/[ÍÌÎÏ]/g, 'i')
  val = val.replace(/[óòõôö]/g, 'o')
  val = val.replace(/[ÓÒÕÔÖ]/g, 'o')
  val = val.replace(/[úùûü]/g, 'u')
  val = val.replace(/[ÚÙÛÜ]/g, 'u')
  val = val.replace(/[ç]/g, 'c')
  val = val.replace(/[Ç]/g, 'c')
  return val.toLowerCase()
}

public searching(search: string) {
  this.gamesCopy = this.games.filter(res => this.slug(res).indexOf(this.slug(search)) > -1)
}

HTML

<input type="text" [(ngModel)]="search" (ngModelChange)="searching($event)">
<ul>
  <li *ngFor="let game of gamesCopy">{{game}}</li>
</ul>

I removed ng-pipes

That's it :)

0

If you don't care about IE support, you can use the normalize method:

<input type="text" [ngModel]="search" (ngModelChange)="onSearchChange($event)">
<ul>
  <li *ngFor="let game of games | filterBy:[]:search">{{game}}</li>
</ul>

onSearchChange(search: string): void {
  this.search = search.normalize('NFKD').replace(/[\u0300-\u036F]/g, '');
}

This will normalize any weird characters you might have.

If you do care about IE, you should find another method from here: Efficiently replace all accented characters in a string?

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149