Search and Replace Different Solution

Search and Replace Different Solution
0.0 0

#1

Tell us what’s happening:
Hi,

this is my solution and it works, but I don’t know if its a good solution or not since i haven’t seen any other similar solution.

If you guys could please tell me what are the good and bad things about this code.

Thank you.

Mauricio

Your code so far

function myReplace(str, before, after) {
	var beforeArr = before.split('');
    var afterArr = after.split('');

    if(beforeArr[0] === beforeArr[0].toLowerCase()){
      afterArr[0] = afterArr[0].toLowerCase();
      afterArr = afterArr.join('');
    } else {
      afterArr[0] = afterArr[0].toUpperCase();
      afterArr = afterArr.join('');
    }
  
    return str.replace(before, afterArr);
}

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36.

Link to the challenge:


#2

I blurred out your solution, since it is a complete solution and we don’t want to ruin it for someone who was looking for help but did not want a complete solution yet.

The one improvement to your code is just to only have the following line used one time (after the if/else statement).

      afterArr = afterArr.join('');

Another improvement would be to just go ahead an set afterArr[0] to uppercase and the only make it lowercase if needed. This eliminates the need for an else statement.

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

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

#3

Hi Randell,
Thank you for your feedback i understand how using that line you mention only once makes it a lot cleaner. And sorry about not blurring the code :frowning: I’ll be more careful next time.