# Question about Intermediate Solution for Search and Replace Challenge

Question about Intermediate Solution for Search and Replace Challenge
0
#1

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!

0 Likes

#2

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!

0 Likes

#3

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.

0 Likes