0

I am trying to set the value of a character at a certain index in a string with a new character and I was wondering if it was possible with charAt() method. Something like this. str.charAt(1) will return string "e" at first.

let str = "hello";
str.charAt(1) = 'a';

str.charAt(1) will then return string "a".

My expected result is that the new string reads "hallo". But this results in an Uncaught ReferenceError: Invalid left-hand side in assignment. So is it simply not possible with this method?

  • 2
    You cannot mutate a String in JavaScript. You can only create a new one, and assign it back to the `str` variable explicitly – blex Mar 12 '20 at 18:24
  • Check this answer https://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript – Nicholas Siegmundt Mar 12 '20 at 18:27
  • 1
    Does this answer your question? [How do I replace a character at a particular index in JavaScript?](https://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript) – Nicholas Siegmundt Mar 12 '20 at 18:27
  • Yes it does. Thanks I understand that they are immutable – Safhossain Mar 12 '20 at 19:01

1 Answers1

0

charAt() is a function on String prototype,and you are trying to overriding it by that syntax; charAt() will return the character at the index and it is getter, not a setter; so you need to define your own custom method to achieve that, either by defining a pure function like snippet below or by defining it on String.prototype so you can use on any string;

let str = "hello";

function replaceStrAtIndex( str, index, letter ){
  let modifiedStr = [...str];
  modifiedStr[index] = letter;
  return modifiedStr.join('')
}
console.log(replaceStrAtIndex(str, 1, 'a'))

or defining on string prototype:

String.prototype.replaceCharAt = function replaceStrAtIndex( index, letter ){
  let modifiedStr = [...this];
  modifiedStr[index] = letter;
  return modifiedStr.join('')
}

let str = "hello";
console.log(str.replaceCharAt( 1, 'a'))
Mechanic
  • 5,015
  • 4
  • 15
  • 38