Javascript: remove accents and spaces

Asked

Viewed 329 times

0

Good afternoon!

Can someone help me solve the problem of how to remove accent and spaces.

When selecting state Alagoas and city Barra de São Miguel, returns thus Barra de São Miguel.html and that should be replaced by barradesaomiguel.html.

Goes below:

Select state Acre Alagoas
    <script type="text/javascript">
    var cidades = [];
   cidades.Acre = ['Rio Branco','Acrelândia','Assis Brasil','Brasiléia','Bujari','Capixaba','Cruzeiro do Sul','Epitaciolândia','Feijó','Jordão','Mâncio Lima','Manoel Urbano','Marechal Thaumaturgo','Plácido de Castro','Porto Acre','Porto Walter','Rodrigues Alves',  'Santa Rosa do Purus','Sena Madureira','Senador Guiomard','Tarauacá','Xapuri'];
   cidades.Alagoas = ['Maceió','Água Branca','Anadia','Arapiraca','Atalaia','Barra de Santo Antônio','Barra de São Miguel','Batalha','Belém','Belo Monte','Boca da Mata','Branquinha','Cacimbinhas','Cajueiro','Campestre','Campo Alegre','Campo Grande','Canapi','Capela','Carneiros','Chã Preta','Coité do Nóia','Colônia Leopoldina','Coqueiro Seco','Coruripe','Craíbas',  'Delmiro Gouveia','Dois Riachos','Estrela de Alagoas','Feira Grande','Feliz Deserto','Flexeiras','Girau do Ponciano','Ibateguara','Igaci','Igreja Nova','Inhapi','Jacaré dos Homens','Jacuípe','Japaratinga','Jaramataia','Jequiá da Praia','Joaquim Gomes','Jundiá','Junqueiro','Lagoa da Canoa','Limoeiro de Anadia','Major Isidoro','Mar Vermelho','Maragogi','Maravilha','Marechal Deodoro','Maribondo','Mata Grande','Matriz de Camaragibe','Messias','Minador do Negrão','Monteirópolis','Murici','Novo Lino','Olho d\'Água das Flores','Olho d\'Água do Casado','Olho d\'Água Grande','Olivença','Ouro Branco','Palestina','Palmeira dos Índios','Pão de Açúcar','Pariconha','Paripueira','Passo de Camaragibe','Paulo Jacinto', 'Penedo','Piaçabuçu','Pilar','Pindoba','Piranhas','Poço das Trincheiras','Porto Calvo','Porto de Pedras','Porto Real do Colégio','Quebrangulo','Rio Largo','Roteiro','Santa Luzia do Norte','Santana do Ipanema','Santana do Mundaú','São Brás','São José da Laje','São José da Tapera','São Luís do Quitunde','São Miguel dos Campos','São Miguel dos Milagres','São Sebastião','Satuba','Senador Rui Palmeira','Tanque d\'Arca','Taquarana','Teotônio Vilela','Traipu','União dos Palmares','Viçosa'];
    // ---
    function updateModels(theForm) 
     { if(theForm.estados.selectedIndex<1){return false; }
       var op=theForm.estados.options;
       var newModels = cidades[op[op.selectedIndex].value];
       theForm.cidades.options.length = 0;
       theForm.cidades.options[0] = new Option("Selecione cidade", "");
       theForm.cidades.options[0].selected = true;
       for (var i=0; i<newModels.length; i++) 
       { theForm.cidades.options[i+1] = new Option(newModels, newModels); }  
     }
    // ---
    // check both selections have been made
     document.getElementById("B1").onclick=function(event)
      { event=event || window.event;
        var targElem = event.target || event.srcElement;
        var thisForm=targElem.parentNode;
        if(thisForm.estados.selectedIndex>0 && thisForm.cidades.selectedIndex>0)
          { var cidadesP= thisForm.cidades;
                  location.href= cidadesP[cidadesP.selectedIndex].value+".html"; }
            else { return false; } 
      }

    </script>
  • place the complete code including the HTML of the form

2 answers

0

Here’s an example of a function that does this:

<script type="text/javascript">

  function remover_acentos_espaco(str) {
  str = str.replace(/^\s+|\s+$/g, ''); // remover espaco do comeco e do fim
  str = str.toLowerCase();
  
  // remover acentuacao
  var from = "ãàáäâèéëêìíïîòóöôùúüûñç·/_,:;";
  var to   = "aaaaaeeeeiiiioooouuuunc------";
  for (var i=0, l=from.length ; i<l ; i++) {
    str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
  }

  str = str.replace(/[^a-z0-9 -]/g, '') // remover caracteres inválidos
    .replace(/\s+/g, '') // Remover espaços
    .replace(/-+/g, ''); //Remover traços
  return str;
}

console.log(remover_acentos_espaco("Barra de São Miguel"));
</script>  

In your browser console text should appear without spaces or accents

  • I’ve tried that and it doesn’t work. There are several cities with accents and spaces.

  • @ricardosac I did a quick test here and apparently the above code works (I have not tested for all cases, so I may be wrong). But if that’s not what you need, just edit your question by putting a few more examples and giving more details about what exactly didn’t work (what cases fails, for example). Complementing, here has some code options to remove the accents, and just join with the above that removes the spaces and believe it will be solved...

  • If you already do replace that removes the spaces, you don’t need the first one that just removes from the beginning and end. Actually, I don’t think you need to do as many regex. Assuming that the problem is just remove everything that is not letter and delete the accents, would it do only str.toLowerCase().normalize('NFD').replace(/[^a-z]/g, '')

0

You are putting the name and value of select as the same in new Option(newModels, newModels)

You can do regex in value, thus:

new Option(newModels, newModels.normalize('NFD').replace(/[^a-z]/g, ''));

Or you can do the regex when you get the value:

Change the line location.href= cidadesP[cidadesP.selectedIndex].value+".html"; }

To

location.href= cidadesP[cidadesP.selectedIndex].value.toLowerCase().normalize('NFD').replace(/[^a-z]/g, '')+".html"; }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.