Reputation: 347
I have this function that replaces an array element at indexOf(before) with a string called "after". This almost works fine except I'm getting two "after" values instead of just one
here is my code:
function myReplace(str, before, after) {
var strArr = [];
strArr = str.split(' ');
for (var i = 0; i < strArr.length; i++) {
strArr.splice(strArr.indexOf(before), 1, after);
}
return strArr;
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
and here what it returns:
["A", "quick", "brown", "fox", "leaped", "over", "the", "lazy", "leaped"]
what is wrong?
Upvotes: 0
Views: 829
Reputation: 446
Array.prototype.splice returns -1 when no element is found : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
So in the first loop, it will replace "jumped" by "leaped" as expected, but for all other, it will do strArr(-1, 1, after)
which means it will replace the last element with after
.
The problem here is your for loop, it checks if before is present for every element in your table. You must use a while loop as in the example provided in the link above (look at Finding all the occurrences of an element)
Upvotes: 1
Reputation: 5189
Use this:
function myReplace(str, before, after) {
var strArr = [];
strArr = str.split(' ');
for (var i = 0; i < strArr.length; i++) {
if(strArr[i] === before){
strArr[i] = after;
}
}
return strArr;
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
Upvotes: 0
Reputation: 68393
If you simply want to replace, then keep it simple
var regex = new RegExp("jumped", "gi");
var output = "A quick brown fox jumped over the lazy dog".replace( regex, "leaped" );
console.log(output);
You can read more about RegExp
here
Upvotes: 1
Reputation: 2833
Ah the problem here is rather unlucky! This is because after it finds element 4, indexOf returns -1 (its way of saying not found), and replaces the last (-1) from the array.
function myReplace(str, before, after) {
var strArr = [];
strArr = str.split(' ');
for (var i = 0; i < strArr.length; i++) {
var index = strArr.indexOf(before);
if(index!=-1){
strArr.splice(index, 1, after);
}
}
return strArr;
}
Hope this helps.
Upvotes: 2