-2

I want to replace a string within an array with another string.
In my example cat should be replaced with mouse:

var arr1 = [ "dog", "cat"];

for(i=0; i<arr1.length; i++){
    arr1[i].replace("cat", "mouse");
}

Unfortunately, the array remains unchanged.

Where is the error?

Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
  • 1
    Strings are immutable – Oriol Mar 12 '16 at 21:38
  • @Oriol: Um, your link doesn't answer this question properly. IMO, he should be using splice instead of replace, since it is an array question more than a straight string question. arr1.splice(arr1.indexOf('cat'), 1,'mouse'); – John Green Mar 12 '16 at 21:42
  • @JohnGreen That replaces the first `'cat'` array entry with `'mouse'`. Presumably, OP wants to replace the first `'cat'` substring of each string array entry with `'mouse'`. Not exactly the same. – Oriol Mar 12 '16 at 21:44
  • @Oriol No, I'd have put it through a loop, which I had written up in my longer explanation before somebody closed the thread. ; ) – John Green Mar 12 '16 at 21:45
  • @JohnGreen Sorry, but I still think it's a dupe, because it asks why `replace` doesn't work, not ways of replacing. If you have an alternative code which solves the problem without `replace`, you can post a new self-answered question, and link it here in the comments. – Oriol Mar 12 '16 at 21:54
  • @Oriol Eh, too much effort. I will say that I think his question was tagged arrays, not replace. His use of replace was just because he didn't think of splice. – John Green Mar 12 '16 at 22:07

2 Answers2

3

That's because you need to reassign the result of the replace back to the element:

var arr1 = [ "dog", "cat"];

for(i=0; i<arr1.length; i++){
    arr1[i] = arr1[i].replace("cat", "mouse");
}
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
3

.replace() returns a new string.

From MDN:

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.

So you should be doing.

arr1[i] = arr[i].replace("cat", "mouse");

Dimitris Karagiannis
  • 8,942
  • 8
  • 38
  • 63