If you already know which index you want (in the latter case), you don’t need to make a for
to reach it, just access it directly. But as the another answer I have already said, strings are immutable and it is not possible to change them this way.
Then an alternative is to get a substring containing all the characters except the last one, and concatenate with the character you want to replace:
let str = 'abc';
// trocar o último caractere por espaço
let nova = str.slice(0, -1) + ' ';
console.log(`[${nova}]`); // imprimir entre colchetes para mostrar o espaço no final
In the case, slice(0, -1)
takes the entire string of the first character (at zero), down to the penultimate (in this case, -1
indicates the last character, but the final index is not included in the result, so it goes to the penultimate) - see the documentation for more details.
The only however is when the string is empty (''
), because in this case the new character is always concatenated. But if you want, you can make this check before:
let nova;
if (str.length == 0) { // string vazia, não troca o caractere
nova = '';
} else {
nova = str.slice(0, -1) + ' ';
}
Do you want to exchange all values equal to what you want? For example: In a word: Illiterate; I want to exchange all 'a'?
– adventistaam
Tried to use str.replace('a','0')?
– adventistaam
No, actually I just want to change the last value, for example: 123, I want 3 to be " ", and then I convert all the value to an integer, in case this would be to be incremented in a button to clear the user’s last digit.
– Fabio Libonati
I edited a little to make my problem clearer.
– Fabio Libonati
You can do it like this:
const b = \
${a. Slice(0, - 1)}_``– adventistaam