Search and Replace2


function myReplace(str, before, after) {
  let x = str.split(" ");
  let regexp = /^[A-Z]/;
  let p=after[0];
  let m = p.toUpperCase();//console.log(m);
  for(let i=0;i<x.length;i++){
     if(before==x[i]){
       let g = x[i];//console.log(g[0]);
       if(g[0]!==m.toUpperCase()){
       //if (regexp.test(g[0])){
          x[i]=after;
          str = x.join(" ");
          console.log(str);
        } else{
            after = after.slice(1);
            after = m+after;
            x[i] = after; 
            str = x.join(" ");
          console.log(str);
       }   
     }
  }
 // console.log(x);
  return str;
}

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

i’m not getting the problem in this code

thank you so much for the modification, i’ll try it once again after debugging

What About This Code ?

function myReplace(str, before, after) {
    let isUpperCase = before[0] === before[0].toUpperCase();
    after = isUpperCase ? after.charAt(0).toUpperCase() + after.slice(1) : after;
    return str.replace(before, after);
}