简体   繁体   中英

Replace accented characters with their unaccented equivalent

I have a text field that can not allow accents. I was using this code:

<input type="text" onkeyup="value=value.replace(/[^0-9a-zA-Z' ']/g,'')">

But rather than blocking the characters, I need them to be replaced for example by typing Ç change to C

I found a function and hes working, but when I type a dot appears the letter A

Can you help me?

<script>function retiraAcento(palavra,obj){  
com_acento = 'áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ<,>´`-,*/~';  
sem_acento = 'aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC          ';  
nova='';  

for(i=0;i<palavra.length;i++) {
if (com_acento.search(palavra.substr(i,1))>=0) {  
    nova+=sem_acento.substr(com_acento.search(palavra.substr(i,1)),1);  
} else {  
    nova+=palavra.substr(i,1);  
} 
}  
obj.value = nova;}</script><input type="text" onKeyUp="javascript:retiraAcento(this.value, this);">

I didn't dig into it enough to see why the . was being replaced with A, but this version doesn't have that behaviour. It doesn't work exactly the same and it operates on the whole string, but that likely isn't a problem unless it's used in a large textfield, in which case it could be optimised other ways.

const com_acento = 'áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ<,>´`-,~';
const sem_acento = 'aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC          ';

function retiraAcento(string) {
    return string
    .split('')
    .map(char => {
        const charIdx = com_acento.indexOf(char)
        if (charIdx !== -1) {
        return sem_acento[charIdx]
      }
      return char
    })
    .join('')
}

function replaceCharOnChange(evt) {
  event.target.value = retiraAcento(evt.target.value)
}

document.querySelector('input').addEventListener('keyup', replaceCharOnChange)

Apologies it's half rewritten in english! I'd also look into using another data structure than the two same-length strings. The simplest would be an object lookup table eg:

{á: 'a', ç: 'c', ...}

but there's other ways you could go about it too

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM