Search and Replace: Why is the advanced solution better than the other solutions in the guide?

Here is the guide.

It just seems like the advanced solution does a lot of extra work and takes up a lot more extra power to use. Would anyone like to explain? If you were going to use this function in a program, which of the provided solutions would be best to use?

Also, here’s my solution if you want to comment on it:

function myReplace(str, before, after) {
  if(before[0].match(/[A-Z]/)) return str.replace(before, after[0].toUpperCase() + after.slice(1));
  return str.replace(before, after);

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

We had a “fun” discussion about this recently: Search and Replace - Better Advanced Solution


Short answer: It’s not.

For some reason, it matches each character of before/after. Which doesn’t address the question.


I couldn’t agree more with you. I like to run on my own algorithm and the basic, intermediate, and advanced solutions. To me, the one that wins is the fastest algorithm.

Here’s my link to Search and Replace jsperf,com tests.

1 Like