14

I got this warning from variable cipher when I was trying to change a string character at specified index.

const emojis: string[] = [/* values */];

function revealOriginEmojis(cipher: string): string {
  for(let i = 0; i < cipher.length; i++){
    let index: number = emojis.indexOf(cipher[i]);

    cipher[i] = emojis[index];
  }

  return cipher;
}

So, should I create a new string variable or any better solutions? Thank you so much

Fanny Hasbi
  • 207
  • 1
  • 2
  • 8
  • In general you could do something like `return origString.split("").map(char => func(char)).join("");` but I am very confused about what `revealOriginEmojis` is supposed to do. `emojis[emojis.indexOf(something)]` is going to either be `something` or the empty string, so are you just filtering the original string or something? – jcalz Apr 12 '20 at 01:22
  • Sorry, the `emojis` const has values. Yes, I want to filter the `index` using *modulo* and used it to get the new index, then change the cipher char at the specified index. – Fanny Hasbi Apr 12 '20 at 10:25

1 Answers1

18

A string is a primitive value, it's immutable.

you can convert it into array of chars, edit some elements of the array and convert back the array into string.

const cipherChars = [...cipher]; // convert into array

cipherChars[2] = 'X'; // alter array

cipher = cipherChars.join(''); // convert back into string
Yukulélé
  • 15,644
  • 10
  • 70
  • 94
  • 2
    if you get error: `Type 'string' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.` you can do `const cipherChars = Array.from(cipher);` see also https://stackoverflow.com/questions/53441292/why-downleveliteration-is-not-on-by-default – Harry Moreno Oct 08 '21 at 17:55
  • 1
    Note that `join()`'s default argument is ",", not "". – DanielM Sep 12 '22 at 08:26