Question about Intermediate Solution for Search and Replace Challenge

Hello. I wondered if the following solution contains unnecessary code (Line 2). The solution is shown on freeCodeCamp Algorithm Challenge Guide: Search and Replace. (2nd solution down).

function myReplace(str, before, after) {
//Create a regular expression object
  var re = new RegExp(before,"gi");
//Check whether the first letter is uppercase or not
  if(/[A-Z]/.test(before[0])){
  //Change the word to be capitalized
    after = after.charAt(0).toUpperCase()+after.slice(1);
     }
     //Replace the original word with new one
  var  newStr =  str.replace(re,after);

 return newStr;
}
// test here
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

What is var re = new RegExp(before,"gi"); 's role in the function? Thanks!

Could I just as well write the code without line 2, so it looks like this:

function myReplace(str, before, after) {
//Check whether the first letter is uppercase or not
  if(/[A-Z]/.test(before[0])){
  //Change the word to be capitalized
    after = after.charAt(0).toUpperCase()+after.slice(1);
     }
     //Replace the original word with new one
  var  newStr =  str.replace(before,after);

 return newStr;
}

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

Thanks!

I found the answer here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Basically, a regexp is being created and passed to re. The first parameter of the new regexp function is the pattern you are looking for. In this case it’s before = “jumped”. The second parameter are the “g” flag which means find all that match “jumped” the “i” flag is saying ignore case, so look for both upper and lower case.

My First Algorithm Worked. Its Easy To Understand: -

function myReplace(str, before, after) {

  if (before[0].match(/^[A-Z]/)){

  var af= after.replace(after[0], after[0].toUpperCase());

  }

  else {

  var af = after.replace(after[0], after[0].toLowerCase());

   }

  return str.replace(before, af);

}

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

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Also, please do not revive 3 year old threads just to post your solution.

Thank you.