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

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

#1

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");


#2

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


#3

Short answer: It’s not.

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


#4

@basantos

I couldn’t agree more with you. I like to run jsperf.com 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.