Search and Replace- how to implement .toUpperCase into both functions

Tell us what’s happening:
//note: is it possible to solve this without using the .replace method?
I tried to solve this problem using two different approaches. Replaceit runs a loop, the second function tries to solve it by splitting into an array by the old string and joining it back into string by the newstring.
I am having problems implementing the following to pass the last round of tests:
if (oldS[0]==oldS[0].toUpperCase()){
newS[0]=newS[0].toUpperCase();
};
Id like to try to implement this into both functions. however when its run it just replaces it without upper casing it so that line of logic is doing nothing?

Your code so far

//method 1
function Replaceit(str, old, newS) {
for (var i=0; i<str.length;i++){
  if (str.substring(i,i+old.length)==old){
    str= str.substring(0,i)+ newS+ str.substring(i+old.length,str.length);
  }
}
return str;
}
Replaceit("Let us go to the store", "store", "mall");

//methid 2
function replaceString(oldS, newS, fullS) {
  if (oldS[0]==oldS[0].toUpperCase()){
     newS[0]=newS[0].toUpperCase();
  };
  console.log(fullS.split(oldS).join(newS));
}
replaceString("Store", "mall", "Let us go to the Store");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace

Strings are immutable. That means you can’t change the data inside a string, like in doing newS[0] = newS[0].toUpperCase()

1 Like

Absolutely. I will not post my code, because we don’t want this thread to become a bunch of challenge solutions, but I will explain my algorithm.

First, I need to check if the case of the first letter of the old word is the same as the uppercase version of the first letter of the old word. If it is, then I need the first letter of the new word to be uppercase, otherwise, the new word will remain the same case as it was passed into the function.

Second, I need to split the string argument into an array of words.

Third, I need to iterate through each word in the words array and if the current word matches the old word, then replace the current word with the new word, otherwise, do not replace.

Last, create a string by joining the words back together with space characters between each word and return this string.

1 Like