[Help] Search and Replace cannot use'join'

[Help] Search and Replace cannot use'join'
0

#1

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…


#2

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


#3

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");

#4


Try this explanation I gave to my High School students.


#5

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


#6

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


#7

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.