Search and replace. Why wont this code work?

Search and replace. Why wont this code work?
0.0 0

#1

Can anyone please explain why this is replacing the first word of the string instead of the word that is === to the ‘before’ argument.

Im not asking for a spoiler, just why this one wont work.

function myReplace(str, before, after) {

var spltStr = str.split(" “);
for(i=0;i<spltStr.length;i++) {
if(spltStr[i]===before) {
spltStr.splice(spltStr[i], 1, after);
}
}
return spltStr.join(” ");
}

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

Result: “leaped quick brown fox jumped over the lazy dog”

Expected result: “A quick brown fox leaped over the lazy dog”


#2

First parameter of splice should have been an integer but you put a string (an element from your array) instead.
http://www.w3schools.com/jsref/jsref_splice.asp

Also the case of “after” word should match the “before” word.


#3

Ah ok thank you very much.