[Help] Search and Replace cannot use'join'

Hello. I’m trying to solve Search and Replace. Here is my code.

function myReplace(str, before, after) {
var res = str.split(" ");
for(var i=0; i < res.length; i++) {
if(res[i] === before) {
return after.replace(before);  }
 }
}

myReplace(“A quick brown fox jumped over the lazy dog”, “jumped”, “leaped”); //“leaped”`

I could print out ‘after’ word but I cannot combine them properly. I tried Array.prototype.join() but it print out with ‘before’ word.

function myReplace(str, before, after) {

var res = str.split(" ");
for(var i=0; i < res.length; i++) {
 if(res[i] === before) {
  after.replace(before);
  return res.join();
  }
 }
 }
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"); 
// A ,quick, brown ,fox, jumped  ,over, the, lazy ,dog

Could you give me some advice what is the problem? Thank you…

after.replace(before) doesn’t do anything.
Read documentation about replace: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Thank you so much for your advice.
I changed my code after reading the documentation. I don’t know why it does not work still…

function myReplace(str, before, after) {

var res = str.split(" ");
for(var i=0; i < res.length; i++) {
if(res[i] === before) {
  var newres = res.replace(before,after);
 return newres.join();
   }
 }
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");


Try this explanation I gave to my High School students.

1 Like

.replace() is a string method, you can’t apply it on arrays (res is an array);

1 Like

Thank you! The exlanation is clear and it helped me to understand what was the problem.

Thank you. I thought it is a good idea to use array… In the end I decided not to use arary and use only string.
Thank you for your feedback.