My solution for "search and replace " challenge

here is my solution and i would love you guys to review my code

function myReplace(str, before, after) {
   
   var sam=str.split(' ');
   var name=before.split(' ');
   for (var i=0; i<sam.length; i++){
  	if(sam[i]===before){
  		if(before[0]===before[0].toUpperCase()){
  			after=after.split('')
  			after[0]=after[0].toUpperCase()
  			after=after.join('')
  			sam[i]=after;
  		}

   		else {sam[i]=after};
   	}
   }
   return sam.join(' ');
}
1 Like

Hey zealsham
I solved it like this. As my dad says there’s more then one way to skin a cat :slight_smile:
I prefer more spaces to make code easier to read but thats just a personal pref.
I was originally using arr.reduce to return the arr to a string but join() was way simpler so i copied that from you.

function myReplace(str, before, after) {
  var substitute, wordArr;
  if(before.charAt(0) == before.charAt(0).toUpperCase()) {
    substitute = after.charAt(0).toUpperCase() + after.slice(1);
  } else {
  substitute = after;
  }
  wordArr = str.split(’ ‘);
  for(var i = 0; i < wordArr.length; i++) {
    if (wordArr[i] === before) {
      wordArr[i] = substitute;
    }
  }
return wordArr.join(’ ');
}

1 Like
function myReplace(str, before, after) {
    after = after.split('');
    before = before.split('');
    if (before[0] == before[0].toUpperCase()) after[0] = after[0].toUpperCase();
    after = after.join('');
    before = before.join('');
    var newStr = str.replace(before, after);
    return newStr;
}

myReplace("He is Sleeping on the couch", "Sleeping", "sitting")
1 Like

elegant and conscice. i like how you did it

1 Like

There is an unused variable name, other than that everything is fine.

Also, you are supposed to use this string method when you replace the old string with new one.

You have split the string into words and replaced the required word, like you would do in earlier challenges. But for the sake of confirming to the present challenge, familiarize (if needed) with String.prototype.replace() and modify your code.

Suggestion :
else {sam[i]=after};

Saving space like thing might mean more head scratching in the future, always format you code neatly! :slight_smile:

Unless the before string is in title case you don’t have to split before and after.

function myReplace(str, before, after) {
    if (before[0] == before[0].toUpperCase()){
      // only split when you need to preserve case of old substring
      after = after.split('');
      before = before.split('');
      after[0] = after[0].toUpperCase();
      after = after.join('');
      before = before.join('');
    } 
    var newStr = str.replace(before, after);
    return newStr;
}

An IF/Else statement should do it

1 Like

some how same here :slight_smile:

1 Like

wow! mine is much longer - but hey it still works!

function myReplace(str, before, after) {

  var newafter;
  var newstr;
  var newWord = [];
  
  if (before.toLowerCase() === before) {
  
  newstr = str.replace(before,after);
  
  } else {
    
    for (i = 0; i<after.length; i++) {
      if (i > before.length-1) {
        var current3 = after[i];
        newWord.push(current3);
      } else if(before[i].toLowerCase() === before[i]){
        var current = after[i];
        newWord.push(current);
      } else {
        var current2 = after[i].toUpperCase();
        newWord.push(current2);
      }
    }

   var joined = newWord.join('');
   newstr = str.replace(before, joined);
    
  }
  
  return newstr;
  
}

This works perfectly fine and easier…

function myReplace(str, before, after) {
var chr =before.charAt(0);

if (chr==chr.toUpperCase()) {
after=after.charAt(0).toUpperCase() + after.substring(1);
}
return str.replace(before,after);
}
myReplace(“A
quick brown fox jumped over the lazy dog”, “jumped”,
“leaped”);

Here is mine:

function myReplace(str, before, after) {
  after = before.toLowerCase().indexOf(before[0]) > -1 ?
    after : after[0].toUpperCase() + after.slice(1);
  
  return str.replace(before, after);
}
2 Likes

Here’s my take on the solution: similar to some of these other solutions:

function myReplace(str, before, after) {
  (before.charAt(0)===before.charAt(0).toUpperCase()) ?
    after=after.slice(0,1).toUpperCase()+after.slice(1)
   :after=after.slice(0,1).toLowerCase()+after.slice(1);
  return str.replace(**new RegExp**(before), after);
}

edit: I just noticed that using a RegExp isn’t necessary, I can just compare with the String itself.

Here is my solution :

function myReplace(str, before, after) {
  let final ="";  
  if(before[0].charCodeAt() < 90)
     after = after.replace(after[0],after[0].toUpperCase());  
  final = str.replace(before,after);
  return final;
}
myReplace("He is Sleeping on the couch", "Sleeping", "sitting");

I used arrays to overlay complete case sensitivity of BeFoRe string onto AfTeR string, ie. check more than the first character.

function myReplace (str, before, after) {

      var boolArr =  before.split("").map(function (bLet) {
        return bLet===bLet.toUpperCase() ? true : false;
      });    
  
      after = after.split("").map(function (aLet) {
        return boolArr[after.indexOf(aLet)] ? aLet.toUpperCase() : aLet.toLowerCase();          
      }).join("");
  
     return str.replace(before,after);
  }
1 Like

Here’s mine. I was afraid of it being too bulky, but it seems like you guys did something similar :slight_smile:

function myReplace(str, before, after) {
  var words = str.split(" ");
  
  for(i = 0; i < words.length; i++){
    
    if(words[i] === before) {
      if(before.charAt(0) === before.charAt(0).toUpperCase()){
         after = after.charAt(0).toUpperCase() + after.slice(1);
         words[i] = after;
      } else {
         words[i] = after;
      }
    }
  }
  return words.join(" ");
}

myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

I need to start writing shorter algorithms. This is my favorite solution :slight_smile:

My short solution using new RegExp. Some posters have stated the new RegExp is not necessary, but if you were to have multiple instances of the word needing to be replaced and you did not use the global attribute (g), then it would only replace the first instance of the word. The FCC challenge does not contain such a test, but it probably should.

function myReplace(str, before, after) {
  if (before[0] == before[0].toUpperCase())
    after = after[0].toUpperCase() + after.slice(1);
  return str.replace(new RegExp(before, 'g'), after);
}
1 Like

My sol’n


function myReplace(str, before, after) {
  after = (before.charAt(0) >= 'A' && before.charAt(0) <= 'Z') ? after.charAt(0).toUpperCase() + after.slice(1) : after;
  return str.replace(before, after);
  
}


Always interesting to see everyone’s solutions. There’s more than one way to skin a cat!

Edit: Noticing a small inconsistency of using before[0] and before.charAt(0) when I could have just one of those methods in this case. I was experimenting with them, I’ll leave it as a remnant of that.

function myReplace(str, before, after) {
  var re = new RegExp(before);
  var upAfter = after.charAt(0).toUpperCase() + after.slice(1);
  
  if (before[0] === before[0].toUpperCase()) {
    str = str.replace(re, upAfter);
  } else {
    str = str.replace(re, after);
  }
  
  return str;
}

Thanks to the ternary operator, I was able to compress my solution down to a single statement. (This passes the test, but only replaces the first occurrence of a word and assumes after is passed into the function in lowercase.)

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