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!

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: