Search and Replace [0] of string

Tell us what’s happening:
I everyone, I have an issue here. This program is working well but I don’t understand why I need to split the ‘after’ string but not the before string. If I do not split the after string I have an error that after[0] doesn’t exist.

Do you know why ?
thank you.

Your code so far

function myReplace(str, before, after) {
  
  //before = before.split('');
  after = after.split('');
  
  if(before[0] === before[0].toUpperCase()){
     after[0] = after[0].toUpperCase();
  }
  
  //before = before.join('');
  after = after.join('');
  
  return str.replace(before, after);
}

myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36.

Link to the challenge:

Hello!

As with many languages, there are multiple ways to handle this without splitting/joining. I personally believe the easiest way is to just recreate the string. See my code sample below:

function myReplace(str, before, after) {
  
  if(before.charAt(0) == before.charAt(0).toUpperCase()) after = after[0].toUpperCase() + after.substring(1);
  return str.replace(before, after);
}

What my statement above does is use built in JS functions to locate the positions instead of arrays. After which I snag the values I need and rebuild the string without having to do any join/splits.

I don’t personally know the exact answer to yours but I felt I would share my solution as well. I believe yours has some sort of conversion to it, perhaps the split invokes a char type object?

1 Like

When I run your code, all tests pass. Try resetting the challenge and pasting your solution in again.

ArielLeslie,

They already know their code works. Their question was to why it doesn’t work if they remove a piece of code, see their example.

If they remove the .split() call on the after variable it throws an error. That is why I suggested in my post that perhaps it adds some sort of unicode or “char” type to the string which throws the error.