4

Estoy implementando una búsqueda (filtro) con los elementos de una tabla, todo funciona muy bien, excepto cuando el usuario utiliza búsquedas sin acentos.

Por ejemplo, en la tabla existen "Luis Perez", "Juan Pérez" y "Pedro Pèrez"

Si el usuario quisiera ver todos los "Perez" y lo escribe tal cual, la búsqueda arrojaría únicamente el apellido sin tilde (Luis), ocultando los demás que están acentuados.

Cómo logro que la búsqueda ignore los acentos?

Estoy utilizando el tutorial de w3schools.com

Este es el código:

<html>
<head>
   	<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('https://www.w3schools.com/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myTable {
  border-collapse: collapse;
  width: 100%;
  border: 1px solid #ddd;
  font-size: 18px;
}

#myTable th, #myTable td {
  text-align: left;
  padding: 12px;
}

#myTable tr {
  border-bottom: 1px solid #ddd;
}

#myTable tr.header, #myTable tr:hover {
  background-color: #f1f1f1;
}
</style>
</head>
<body>

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Buscar..." title="Type in a name">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Country</th>
  </tr>
  <tr>
    <td>Luis Perez</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Juan Pérez</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>Pedro Pèrez</td>
    <td>UK</td>
  </tr>

</table>



<script>

function myFunction() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}
</script>

</body>
</html>

2 respuestas 2

6

Podrías implementar una función que elimine los acentos(tanto en el input del usuario como en los valores de la tabla, esto para poder usar indexOf):

var accent_map = {'á':'a', 'é':'e', 'è':'e', 'í':'i','ó':'o','ú':'u','Á':'a', 'É':'e', 'è':'e', 'Í':'i','Ó':'o','Ú':'u'};
function accent_fold (s) {
  if (!s) { return ''; }
  var ret = '';
  for (var i = 0; i < s.length; i++) {
    ret += accent_map[s.charAt(i)] || s.charAt(i);
  }
  return ret;
};

De esta forma, el input queda sin acentos, y se compara con los valores de la tabla, también sin acentos. El ejemplo quedaría así:

<html>
<head>
   	<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('https://www.w3schools.com/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myTable {
  border-collapse: collapse;
  width: 100%;
  border: 1px solid #ddd;
  font-size: 18px;
}

#myTable th, #myTable td {
  text-align: left;
  padding: 12px;
}

#myTable tr {
  border-bottom: 1px solid #ddd;
}

#myTable tr.header, #myTable tr:hover {
  background-color: #f1f1f1;
}
</style>
</head>
<body>

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Buscar..." title="Type in a name">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Country</th>
  </tr>
  <tr>
    <td>Luis Perez</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Juan Pérez</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>Pedro Pèrez</td>
    <td>UK</td>
  </tr>

</table>



<script>
var accent_map = {'á':'a', 'é':'e', 'è':'e', 'í':'i','ó':'o','ú':'u','Á':'a', 'É':'e', 'è':'e', 'Í':'i','Ó':'o','Ú':'u'};
function accent_fold (s) {
  if (!s) { return ''; }
  var ret = '';
  for (var i = 0; i < s.length; i++) {
    ret += accent_map[s.charAt(i)] || s.charAt(i);
  }
  return ret;
};

function myFunction() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = accent_fold(input.value).toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      if (accent_fold(td.innerHTML).toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}
</script>

</body>
</html>

El tutorial completo podés verlo aquí, se llama 'accent folding':

https://alistapart.com/article/accent-folding-for-auto-complete

1
  • Gracias! Me funciona perfectamente. el 11 sep. 2018 a las 18:32
5

Tuve un problema similar y creo hay una manera más sencilla:

Podrías intentar remplazando

if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {

Con algo similar a esto:

if (td.innerHTML.normalize("NFD").replace(/[\u0300-\u036f]/g, '').toUpperCase().indexOf(filter) > -1) {

Lo que va a hacer es:

  1. normalize("NFD") separa las tildes de los caracteres acentuados
  2. .replace(/[\u0300-\u036f]/g, '') los elimina (los remplaza con '')

Crédito / links de referencia:

1
  • 1
    Gracias Jos, voy a revisarlo y tenerlo en cuenta para futuras consultas. A propósito, bienvenido! el 1 oct. 2020 a las 15:37

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.