Search and Replace feedback on solution


// second arg is the word that you will be replacing (before)

// third arg is what you will be replacing the second argument with (after)

// preserve the case of the first character in the original word when replacing it.

// Example....if you mean to replace the word Book with the word dog, it should be replaced as Dog

// Ex..('Let us go to the store', 'store', 'mall') should return the string 'Let us go to the mall'

function myReplace(str, before, after) {
  let beforeIndex = 0;
  let splitStr = str.split(/[\W_]/);
  let upperRegex = /^[A-Z]/;
  let lowerRegex = /^[a-z]/;
  let finalStr;

  for (let word in splitStr) {
  
    if (splitStr[word].includes(before)) {
      if (upperRegex.test(splitStr[word])) {
        splitStr[word] = after;
        finalStr = splitStr[word][0].toUpperCase() + splitStr[word].slice(1).toLowerCase();
        splitStr[word] = finalStr;      
      } else if (lowerRegex.test(splitStr[word])) {
        splitStr[word] = after;
      }

      if (splitStr[word].includes(after)) {
        if (upperRegex.test(before)) {
          finalStr = splitStr[word][0].toUpperCase() + splitStr[word].slice(1).toLowerCase();
          splitStr[word] = finalStr;
        } else if (lowerRegex.test(before)) {
          finalStr = splitStr[word].toLowerCase();
          splitStr[word] = finalStr;
        }
      }
    }
  }
  
  let finishedStr = splitStr.join(' ');
  console.log(finishedStr)
  return finishedStr;
}

myReplace("I think we should look up there", "up", "Down");

Hello all! I have completed the search and replace algorithm challenge but my solution seems very long and I was wondering if it is even remotely good? Thanks for reading and giving me feedback!

Michael Johnson

Your code is indeed working, and it is readable, even it is a bit long - so good job.

Since you’ve solved this problem, it will be no harm to look into solutions from this step’s guide. For this step there are 5 solutions, I am sure you will find there techniques for writing more concise solution.

1 Like

Thanks so much! That makes me feel better and that I am actually getting somewhere :). The intermediate algorithms seem so easy at first until you get deep into them and then you realize that you need more practice, haha! That’s kind of the reason I wanted to check for feedback against some of these. Now it’s time to work on improving and optimizing more! Thanks again for reading and giving feedback!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.