How to swap the last character in a string?

Asked

Viewed 149 times

3

I’m having a problem at the time of leaving the last null value to be inserted in a button that will erase the value that the user type, I tried to use the for to solve this problem, but did not solve.

Would anyone know what might be going on?

for (var j = 0;j < getNum.length;j++) {
    if (getNum.length-1 == j) {
          getNum[j] = " ";
          alert(getNum[j]);
    }
    alert(getNum);
}
  • Do you want to exchange all values equal to what you want? For example: In a word: Illiterate; I want to exchange all 'a'?

  • Tried to use str.replace('a','0')?

  • 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.

  • I edited a little to make my problem clearer.

  • You can do it like this: const b = \${a. Slice(0, - 1)}_``

2 answers

5

First, if you just want to "swap" the last string value, the for is not even necessary. Following the logic of the question code, could do so:

getNum[getNum.length - 1] = " ";

However, this doesn’t work because strings are immutable in Javascript. This way, you cannot restore a character by its index in this way (similar to what is done with arrays).

You must create one new string. In your case, you can use the method String.prototype.replace together with a regular expression to replace the last character of the string. Something like this:

const str = 'Foo Bar Baz';
const newStr = str.replace(/.$/, ' ');

console.log({ newStr });

The regular expression I used is very simple:

.$

It will basically select any character (.) at the end ($) of the string. Learn more about the replace here.

  • Thanks for the answer, solved here, I only made a small change in const newStr = str.replace(/.$/, '); exchanging ' ' for '', since I realized that I could not have space at the time to load the command again, as for the link I will take a look, 'cause it seems like there’s a lot of interesting stuff.

  • @Fabiolibonati then participate by voting on the answer as correct ;-)

5

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) + ' ';
}
  • Or you can use the string template \${str.Slice(0,-1)}_``

Browser other questions tagged

You are not signed in. Login or sign up in order to post.