Alex Wulff Alex Wulff - 6 months ago 11
Javascript Question

Remove All Instances of String in Array Javascript

Let's say I have an array with the following contents:

"@@@Some Text###","@@@More Text###","@@@Even more Text###","@@@Even Even More Text###"


And I wanted to remove all instances of
@@@
and
###
. I tried to do this with the following function, but the returned array is exactly the same, as seen in this fiddle:

function removeText(start, end, array) {
var newArray = [];
for (var i = 0; i < array.length; i++) {
var text = array[i];
text.split(start).join("");
text.split(end).join("");
newArray.push(text);
}

return newArray;
}


I assume that there is some very simple reason that I can't get this to work, so any help would be appreciated. Thanks!

Answer

The split method doesn't modify the original string, instead it returns a new value, so make sure that you reassign it to text so that you are actually modifying the array[i] instance:

text = text.split(start).join("");
text = text.split(end).join("");

And here's your updated fiddle.