Reputation: 1755
Hey guys im working on a problem that searches the string and replaces x with y in my case before & after. But for some reason my splice() method is just returning the deleted element. and thats where im actually stuck at..... Take a look at my code below, thanks
function replace(str, before, after) {
/* logic
1. put the string into an array with split()
2. search array index and replace 2nd argument with 3rd argument
3. turn array back into string wtih join() method
*/
// turn string into an array
var strIntoArray = str.split(' ');
// looping thru array
for( i = 0; i < strIntoArray.length; i++){
//compare index to arguments
if (strIntoArray[i] === before) {
// replace index with arguments with splice() method
// this part is a lot more complex
console.log(strIntoArray.splice(strIntoArray.indexOf(before), 1, after));
}
}
//console.log(strIntoArray);
}
replace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
Upvotes: 0
Views: 50
Reputation: 644
That's how splice() works. It returns the removed element, but changes the original array. If you output strIntoArray, the change should be made.
Upvotes: 2