Search and Replace2

Search and Replace2
0.0 0

#1

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");

#2

i’m not getting the problem in this code


#3

I have modified your original code to make it more readable, by using more descriptive variable names. This makes it easier to debug. The problem with your code, is that it needs to check the first letter of before and if it is uppercase, then the after needs to be uppercase also in the final string.

function myReplace(str, before, after) {
	let words = str.split(' ');
	let regexp = /^[A-Z]/;
	let firstLetterOfAfter = after[0];
	let capitalizedFirstLetterOfAfter = firstLetterOfAfter.toUpperCase(); //console.log(capitalizedFirstLetterOfAfter);
	for (let i = 0; i < words.length; i++) {
		if (before == words[i]) {
			let firstLetterOfCurrWord = words[i]; //console.log(g[0]);
			if (firstLetterOfCurrWord[0] !== capitalizedFirstLetterOfAfter.toUpperCase()) {
				//if (regexp.test(firstLetterOfCurrWord[0])){
				words[i] = after;
				str = words.join(' ');
				console.log(str);
			} else {
				after = after.slice(1);
				after = capitalizedFirstLetterOfAfter + after;
				words[i] = after;
				str = words.join(' ');
				console.log(str);
			}
		}
	}
	// console.log(x);
	return str;
}
myReplace('His name is Tom', 'Tom', 'john');

#4

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