TransWikia.com

Buscador interno con acentos

Stack Overflow en español Asked by AvrSoft on February 6, 2021

quisiera poder mejorar un buscador interno para que pueda leer palabras con acentos de una base de datos sin necesidad de escribir los acentos en el buscador. Tengo otro buscador que si puedes buscar palabras sin acentos. Por ejemplo: busco mi nombre”Rubén”. En la base de datos consta como “Rubén” pero en el buscador voy a escribir “ruben”. Espero me podáis ayudar.

Os paso el código del search que quiero mejorar:

HTML:

<!DOCTYPE html>
<html>
 <head>
  <title>Buscador interno</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <style>
  #result {
   position: absolute;
   width: 100%;
   max-width:870px;
   cursor: pointer;
   overflow-y: auto;
   max-height: 400px;
   box-sizing: border-box;
   z-index: 1001;
  }
  .link-class:hover{
   background-color:#f1f1f1;
  }
  </style>
 </head>
 <body>
  <br /><br />
  <br /><br />
  <br /><br />
  <br /><br />
  <br /><br />
  <div class="container" style="width:900px;">

   <div align="center">
    <input type="text" name="search" id="search" placeholder="Buscar ciudad" class="form-control" />
   </div>
   <ul class="list-group" id="result"></ul>
   <br />
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 $.ajaxSetup({ cache: false });
 $('#search').keyup(function(){
  $('#result').html('');
  $('#state').val('');
  var searchField = $('#search').val();
  var expression = new RegExp(searchField, "i");


  $.getJSON('js/data.json', function(data) {

   $.each(data, function(key, value){
    if (value.ciudad.search(expression) != -1 )
    {
     $('#result').append('<li class="list-group-item link-class"><img src="'+value.image+'" height="40" width="40" class="img-thumbnail" /> '+value.ciudad+' | <span class="text-muted">'+value.provincia+'</span></li>');

    }
   });   
  });
 });

 $('#result').on('click', 'li', function() {
  var click_text = $(this).text().split('|');
  $('#search').val($.trim(click_text[0]));
  $("#result").html('');
 });
});
</script>

JSON:

[
  {
    "ciudad":"Ruben",
    "image": "https://www.madridiario.es/fotos/1/Los_pueblos_mA_s_bonitos_de_Madrid.jpg",
    "provincia":"MADRID"
  },

    {
    "ciudad":"Rubn",
    "image": "https://www.madridiario.es/fotos/1/Los_pueblos_mA_s_bonitos_de_Madrid.jpg",
    "provincia":"MADRID"
  }

]

Os paso el código del search que funciona sin escribir el acento en el search:

HTML:

<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="css/jquery-ui.css">  
  <script src="js/jquery-1.12.4.js"></script>
  <script src="js/jquery-ui.min.js"></script>
   <script src="js/autocomplete-ok.js"></script>


</head>
<body>

<div>
  <form>

  <input id="developer">
  </form>
</div>



<div>
  <form>

  <input id="developer2">
  </form>
</div>

</body>
</html>

$( function() {
var names = [ “Jörn”, “Scott “, “John2” ];

    var accentMap = {
      "á": "a",
      "ö": "o"
    };
    var normalize = function( term ) {
      var ret = "";
      for ( var i = 0; i < term.length; i++ ) {
        ret += accentMap[ term.charAt(i) ] || term.charAt(i);
      }
      return ret;
    };

    $( "#developer" ).autocomplete({
      source: function( request, response ) {
        var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
        response( $.grep( names, function( value ) {
          value = value.label || value.value || value;
          return matcher.test( value ) || matcher.test( normalize( value ) );
        }) );
      }
    });
  } );

  $( function() {
    var names = [ "1", "2 ", "3" ];

    var accentMap = {
      "á": "a",
      "ö": "o"
    };
    var normalize = function( term ) {
      var ret = "";
      for ( var i = 0; i < term.length; i++ ) {
        ret += accentMap[ term.charAt(i) ] || term.charAt(i);
      }
      return ret;
    };

    $( "#developer2" ).autocomplete({
      source: function( request, response ) {
        var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
        response( $.grep( names, function( value ) {
          value = value.label || value.value || value;
          return matcher.test( value ) || matcher.test( normalize( value ) );
        }) );
      }
    });
  } );

La función:

$( function() {
var names = [ “Jörn”, “Scott “, “John2” ];

    var accentMap = {
      "á": "a",
      "ö": "o"
    };
    var normalize = function( term ) {
      var ret = "";
      for ( var i = 0; i < term.length; i++ ) {
        ret += accentMap[ term.charAt(i) ] || term.charAt(i);
      }
      return ret;
    };

    $( "#developer" ).autocomplete({
      source: function( request, response ) {
        var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
        response( $.grep( names, function( value ) {
          value = value.label || value.value || value;
          return matcher.test( value ) || matcher.test( normalize( value ) );
        }) );
      }
    });
  } );

  $( function() {
    var names = [ "1", "2 ", "3" ];

    var accentMap = {
      "á": "a",
      "ö": "o"
    };
    var normalize = function( term ) {
      var ret = "";
      for ( var i = 0; i < term.length; i++ ) {
        ret += accentMap[ term.charAt(i) ] || term.charAt(i);
      }
      return ret;
    };

    $( "#developer2" ).autocomplete({
      source: function( request, response ) {
        var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
        response( $.grep( names, function( value ) {
          value = value.label || value.value || value;
          return matcher.test( value ) || matcher.test( normalize( value ) );
        }) );
      }
    });
  } );

One Answer

puedes utilizar esta funcion a ver si te sirve:

function as(s){
 let a=["á","é","í","ó","ú","a","e","i","o","u"];
 let str="";
 for(let i=0; i<s.length; i++){
 	let tmp = s[i];
    for(let x=0; x < a.length-5; x++){
       if(tmp.toLowerCase() == a[x]){ tmp === tmp.toLowerCase() ? tmp=a[x+5] : tmp=a[x+5].toUpperCase();}
    }
    str+=tmp;
  }
  return str;
}
alert(`${as("RECÓRTALO")} ${as("suprímelo")} ${as("inútil! xD")}`);
// o modo avanzado:
function adv_as(s) {
return s
       .normalize('NFD')
       .replace(/([^nu0300-u036f]|n(?!u0303(?![u0300-u036f])))[u0300-u036f]+/gi,"$1")
       .normalize();
}
console.log(`${adv_as("RECÓRTALO")} ${adv_as("suprímelo")} ${adv_as("inútil! xD")}`);

advance mode fuente:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize

Answered by Bryro on February 6, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP