0

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);">
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Dani Carla
  • 65
  • 6
  • https://stackoverflow.com/questions/18123501/replacing-accented-characters-with-plain-ascii-ones – curlyBraces Aug 30 '18 at 14:33
  • 2
    Possible duplicate of [Remove accents/diacritics in a string in JavaScript](https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript) – Zzirconium Aug 30 '18 at 14:36
  • Possible duplicate of [Replacing accented characters with plain ascii ones](https://stackoverflow.com/questions/18123501/replacing-accented-characters-with-plain-ascii-ones) – Adam Chubbuck Aug 30 '18 at 14:36
  • 1
    I admit that it's better to replace `á` with `a` than `�`, but it's *much* better to fix the reason your text field does not allow accents in the first place. Only strip accents as a last resort. The world is better with Unicode - we should use it if possible. – Wyck Aug 30 '18 at 14:59

1 Answers1

2

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

Ross Mackay
  • 940
  • 4
  • 10