Handle accent with Jquery

1

I'm having trouble handling accentuation in jQuery.

I would like to remove accents from words and replace spaces with "% 20". I tried to do it the way it did, though, it did not work.

cidade_sem_tratar = $('#estados').val();
console.log(cidade_sem_tratar);

cidade_tratada = cidade_sem_tratar
.replace(/[áàâã]/,'a')
.replace(/[éèê]/,'e')
.replace(/[óòôõ]/,'o')
.replace(/[úùû]/,'u')
.replace(' ','%20');
console.log(cidade_tratada);

The result is as follows:

Could you please help me?

Hug and Thanks!

    
asked by anonymous 29.11.2017 / 14:26

3 answers

1

Your code is correct for replacing accents, but to replace ALL spaces, change the last replace to:

.replace(/\s/g,'%20')

As it stands, it will replace only the first space that is found.

See working:

cidade_sem_tratar = $('#estados').val();
console.log(cidade_sem_tratar);

cidade_tratada = cidade_sem_tratar
.replace(/[áàâã]/,'a')
.replace(/[éèê]/,'e')
.replace(/[óòôõ]/,'o')
.replace(/[úùû]/,'u')
.replace(/\s/g,'%20');
console.log(cidade_tratada);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="estados" value="Afonso Cláudio" />

Using Function

function remAcentos(v){
   var c='áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ';
   var s='aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC';
   var n = '';
   for(var x=0;x<v.length;x++){
      c.search(v.substr(x,1))>=0 ?
      n+=s.substr(c.search(v.substr(x,1)),1) :
      n+=v.substr(x,1);
   }
   return n;
}

cidade_sem_tratar = $('#estados').val();
console.log(cidade_sem_tratar);
cidade_tratada = remAcentos(cidade_sem_tratar).replace(/\s/g,'%20');
console.log(cidade_tratada);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="estados" value="Afonso Cláudio" />
    
29.11.2017 / 15:06
1

Make sure the encodeURI function does what it wants, for example:

var myStr = "Afonso Cláudio";
var res = encodeURI(myStr);

function to remove accents:

function removerAcentos( newStringComAcento ) {
  var string = newStringComAcento;
  var mapaAcentosHex    = {
    a : /[\xE0-\xE6]/g,
    A : /[\xC0-\xC6]/g,
    e : /[\xE8-\xEB]/g,
    E : /[\xC8-\xCB]/g,
    i : /[\xEC-\xEF]/g,
    I : /[\xCC-\xCF]/g,
    o : /[\xF2-\xF6]/g,
    O : /[\xD2-\xD6]/g,
    u : /[\xF9-\xFC]/g,
    U : /[\xD9-\xDC]/g,
    c : /\xE7/g,
    C : /\xC7/g,
    n : /\xF1/g,
    N : /\xD1/g
};

for ( var letra in mapaAcentosHex ) {
    var expressaoRegular = mapaAcentosHex[letra];
    string = string.replace( expressaoRegular, letra );
}

return string;
}

You can use the removeAcentos function and then encodeURI to put% 20 in the spaces

    
29.11.2017 / 15:07
0

The replace in javascript works with regex, and you are not passing a regex to change the spaces. try to put it like this:

string.replace(/ /g, '%20');

You can test regex on sites like this, for example: link

    
29.11.2017 / 15:16