It is always important to understand the mistakes we have made in order to evolve. In this sense your case the code even came close to working.
The biggest problem was the nome[i].CharAt
that is not correct and it is like trying to do both at the same time. Only nome[i]
already get a string representing the letter at the position i
and the same goes for nome.charAt(i)
, now you cannot use both at the same time. As the result is a letter you cannot compare with a number >=0
, but can do it in the form of string
See how correcting these two points already get 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, the console.log
It was typed to a digit, so it wasn’t very useful. It would be better to return the built value, which you can do if you accumulate each digit you interpret from 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 have not removed it on purpose, but it is something you should remove. Do not leave things in the code that you do not use, because this makes it difficult to read and ends up confusing anyone who reads the code. More useful would be to receive the id of the <input>
who wants to interpret Cpf and thus was able to use the function to obtain a Cpf without numbers from any field.