0

I am doing a algorithm in freeCodeCamp.(https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace)

The task is as below:

Perform a search and replace on the sentence using the arguments provided and return the new sentence. First argument is the sentence to perform the search and replace on. Second argument is the word that you will be replacing (before). Third argument is what you will be replacing the second argument with (after).

Note: Preserve the case of the first character in the original word when you are replacing it. For example if you mean to replace the word "Book" with the word "dog", it should be replaced as "Dog"

**
myReplace("Let us get back to more Coding", "Coding", "algorithms") should return "Let us get back to more Algorithms". myReplace("Let us go to the store", "store", "mall") should return "Let us go to the mall".

**

  //if the before is uppercase, the after should be uppercase also 
  // str = str.replace(before, after);
  var regex = /[A-Z]+/g; //check for uppercase
  var newStr = "";
  console.log(regex.test(before));
  if (regex.test(before)) {
    //if uppercase, return true, "after" convert to uppercase
    after = after.toUpperCase();
    newStr = after[0];
    for (var i = 1; i < after.length; i++) {
      //start at index=1 letter, all convert to 
      newStr += after[i].toLowerCase();
    }
    console.log(newStr);
    str = str.replace(before, newStr);
  } else {
    str = str.replace(before, after);
  }
  // console.log(newStr);
  console.log(str);
  return str;
}

I think there should be OK for the code, but can anyone help find why the if statement can't work. Much thanks!

auntR
  • 150
  • 1
  • 2
  • 15
  • Well, for starters, your regex needs to be an object - like `var regex = RegExp('/[A-Z]+/g');` - then you need to make sure your regular expression is correct. This link might help https://stackoverflow.com/a/47661343/600486 – blurfus Feb 21 '20 at 06:40

3 Answers3

1

The problem is that you're calling regex.test() multiple times on the same regular expression instance.

[...]
  var regex = /[A-Z]+/g; //check for uppercase
  var newStr = "";
  console.log(regex.test(before));
  if (regex.test(before)) {
    //if uppercase, return true, "after" convert to uppercase
    after = after.toUpperCase();
[...]

If your string is Hello_there, the first regex.test() will return true, because Hello matched. If you call regex.test() again with the same regex instance, it will have advanced in the string, and try to match starting with _there. In this case, it will fail, because _there does not begin with a capital letter between A and Z.

There are a lot of ways to fix this issue. Perhaps the simplest is to store the result of the first call to a variable, and use it everywhere you're calling regex.test():

[...]
  var regex = /[A-Z]+/g; //check for uppercase
  var newStr = "";
  var upper_check = regex.test(before);
  console.log(upper_check);
  if (upper_check) {
[...]
0

It seems overkill to use a regex, when you really need to only check the first character. Your regex will find uppercase letters anywhere...

If the assignment is to only change one occurrence, then a regex is not really the right tool here: it does not really help to improve the code nor the efficiency. Just do:

function myReplace(str, before, after) {
    if (before[0] === before[0].toUpperCase()) {
        after = after[0].toUpperCase() + after.slice(1);
    } else {
        after = after[0].toLowerCase() + after.slice(1);
    }

    return str.replace(before, after);
}
trincot
  • 317,000
  • 35
  • 244
  • 286
0
function myReplace(str, before, after) {

  var upperRegExp = /[A-Z]/g
  var lowerRegExp = /[a-z]/g

  var afterCapitalCase = after.replace(/^./, after[0].toUpperCase());
  
  if (before[0].match(upperRegExp)) {
    return str.replace(before, afterCapitalCase)
  } else if (after[0].match(upperRegExp) && before[0].match(lowerRegExp)) {
    return str.replace(before, after.toLowerCase());
  } else {
    return str.replace(before, after)
  }
}
Nickoo
  • 1
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 08 '22 at 18:39