It is always important to realize the mistakes we make in order to evolve. In this sense your code even came close to staying up and running.
The biggest problem was nome[i].CharAt
that is not correct and it's like trying to do both at the same time. Only nome[i]
already gets you a string that represents the letter at position i
and the same goes for nome.charAt(i)
, now you can not use both at the same time. As the result is a letter also can not compare with a number >=0
, but can do it in the form of string
See how correcting these two points already yields a result close to what you expected:
function sem(argument) {
var nome = document.getElementById('cpf').value;
for(var i=0;i<nome.length;i++)
{
if (nome[i] >= '0' && nome[i] <= '9') {
console.log(nome[i]);
}
}
}
sem();
<input id="cpf" value="340.905.290-93">
Although it already works, console.log
has been digit-by-digit, so it will not be very useful. It would be best to return the constructed value, which you can do if you accumulate each digit that interprets the original string:
function sem(argument) {
var nome = document.getElementById('cpf').value;
var cpfSemPontos = ""; //nova variavel para ir acumulado os digitos
for(var i=0;i<nome.length;i++)
{
if (nome[i] >= '0' && nome[i] <= '9') {
cpfSemPontos += nome[i]; //concatena o novo digito
}
}
return cpfSemPontos; //devolve no fim
}
cpfSemPontos = sem();
console.log(cpfSemPontos);
<input id="cpf" value="340.905.290-93">
Note that you are not using the parameter you defined in the function, and that I did not deliberately remove it, but it is something that you should remove. Do not leave things in the code you do not use, as this makes readability difficult and ends up confusing anyone who reads the code. More useful would be to get the id of the <input>
that wants to interpret the cpf and thus could use the function to get a cpf without numbers from any field.