Search And Replace string split method

Search And Replace string split method


So I created this function but i have an error:

TypeError: Cannot assign to read only property ‘0’ of string ‘sitting’

function myReplace(str, before, after) {
  var arr = str.split(" ");
  for(var i = 0; i < arr.length + 1; i++)
      if(arr[i] == before)
          if(before[0] === before[0].toUpperCase())
              after[0] = after[0].toUpperCase();
              arr[i] = after;
  return arr.join(" ");

myReplace("He is Sleeping on the couch", "Sleeping", "sitting");```


You’re trying to access the first letter of a string using array bracket notation (before[0]), but you could only do that if you first converted your string to an array.


Oh, that’s why i could read first sign of string but not replace it. Thanks!


@jezzaho - Actually, @LightningCoding is incorrect. You can access strings with bracket notation the same as arrays. There is no need to convert the array to a string. What you can not do is mutate an existing string contained in a variable. You attempt to do this in the following line of code:

after[0] = after[0].toUpperCase();

You are trying to mutate/modify a single character in the string (with after[0]) and JavaScript does not allow this and hence the error message. Instead you need to rebuild the word and then assign the built word to arr[i]. You have some other logic to build in to solve all the tests, but correcting this will get you closer.


Thank You for your great answer :slight_smile: Everything is clear for me now :smile:


@jezzaho I apologize for any confusion my answer may have caused.

I’m not a native English speaker and i’m still learning the language.

You may ignore my answer.


Nothing happen :slight_smile: I want to thank you for your answer and time also, besides that i think thst answer wasn’t bad after solving the problem, it was a mental shortcut :smile: