Search and Replace algorithm - please review code :)

Search and Replace algorithm - please review code :)
0

#1

This code works, but it’s my first time creating additional functions to make the desired one work, so I would really like some feedback on my code. Would really appreciate it! :slight_smile:

function myReplace(str, before, after) {
  var result;
  
  // check if before's first letter is uppercase or not, to preserve the case of original word 
  if (isFirstUpperCase(before)) {
    result = str.replace(before, toFirstUpperCase(after));    
  } else {
    result = str.replace(before, after);
  }
  
  return result;
}

// function to check whether first character of a string is uppercase
function isFirstUpperCase(string) {
  return (string[0] === string[0].toUpperCase()); 
}

// function to convert first character of a string to uppercase 
function toFirstUpperCase(string) {
  return string[0].toUpperCase() + string.substr(1);  
}

#2

Congrats to write additional function for the first time! the way you wrote the code is great. But you can get the same result without writing any function. Please review the code below-

function myReplace(str, before, after) {

// check the first character of the before parameter is uppercase
if (before[0] === before[0].toUpperCase()){
// if yes, convert the first character of after parameter to uppercase and replace with before.
result = str.replace(before, after[0].toUpperCase() + after.slice(1));
}
else{
// simply replace parameter after with beore.
result = str.replace(before, after);
}
return result;

}

Happy Coding :slight_smile: