Quiz search and replace, need help

function myReplace(str, before, after) {
  let newArr1 = []
  let arr = str.split(" ");
  console.log(arr);
  let beforeArr = before.split(" ");
console.log(beforeArr);
let register = beforeArr.join("").match(/[A-Z]/);
newArr1.push(register)
console.log(newArr1.length);
let newAfter;
if (newArr1.length > 0){
 newAfter = after.charAt(0).toUpperCase() + after.slice(1);
console.log(newAfter);
  return newAfter;
}
console.log(newAfter);
for (let i = 0; i < arr.length; i++) { 
if (arr[i]== beforeArr){
 let num =  arr.indexOf(arr[i]); 
delete arr[i];
return arr.splice(num , 1 ,newAfter );
}                       

}
 console.log(arr.join(" "));


  return arr.join(" ");
}

myReplace("His name is Tom", "Tom", "john");

Who can tell what is wrong with function?
I can not get newAfter from if else statement…
link: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace