One of the problems was putting the condition index >= dados.length - 4
. Like index
starts at zero if dados
has size 10, for example, the condition will be false, since zero is not greater than or equal to 6, then the for
will not execute any iteration.
Another problem is that the return
is inside the for
, then in the first iteration it would already return, without iterating by the other characters.
Anyway, you don’t have to use replace
, because you only need to have an amount of #
equal to string size less 4.
One way to do it is to fill in the result with #
until dados.length - 4
, and then pick up the last 4 characters of the string using slice
:
function criptografar(dados) {
let result = "";
for (let index = 0; index < dados.length - 4; index++) {
result += "#";
}
// juntar os # com os 4 últimos caracteres da string
return result + dados.slice(-4);
}
console.log(criptografar('Alexandre'));
console.log(criptografar('abcde'));
console.log(criptografar('ab'));
If the string has 4 characters or less, it does not enter the for
, and slice
returns the entire string.
Another alternative is to use repeat
to construct the string containing the #
:
function criptografar(dados) {
if (dados.length > 4) {
return "#".repeat(dados.length - 4) + dados.slice(-4);
}
return dados;
}
console.log(criptografar('Alexandre'));
console.log(criptografar('abcde'));
console.log(criptografar('ab'));
If the string size is greater than 4, I create a string with "size - 4" characters #
concatenated with the last 4 characters. If the size is less than or equal to 4, it does not enter the if
and returns the entire string, no modifications.
I also put a semicolon at the end of the lines. It may seem "freshness", but this avoids some bizarre situations which may occur if you don’t use them (see more about this here).
Sometimes I think people are overreacting to negative questions here in stack overflow. The description of the problem is clear, the problem is, in theory, reproducible, etc. etc. Add to this that there was no justification for the negative point.
– user142154
Really, an honest doubt, I tried to be as clear as possible. Personal weighs a lot at hand, unfortunately.
– zangs