Reputation: 97
I have a JavaScript function that replaces special characters with normal characters.
When I type a period .
it's changed to a
Example : [email protected]
is changed to info@exampleacom
What am I doing wrong?
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.toUpperCase();
obj.value = nova
}
$(document).ready(function () {
$(":input").live('blur', function () {
retiraAcento(this.value, this);
});
});
Upvotes: 1
Views: 487
Reputation: 437336
String.search
accepts a regular expression as an argument, not a dumb string. The character .
has special meaning inside a regular expression; it means "match any character".
Therefore when your code ends up doing com_acento.search(".")
the result is always 0
: the dot matches the first character. In addition, there are other characters with special meaning in regular expressions which will also cause your code to not work correctly.
Solve your problem by using indexOf
instead of search
.
Upvotes: 4