0

I'm trying to replace part of a string with a different string, but the original string has multiple instances of the string I want to replace and replace() only replaces the first instance.

newString = "New String!"
testString = testString.replace("Old String?", newString);

I've also tried the global flag 'g' but I think my implementation was incorrect.

  • would have been helpful to see your implementation of the global flag so that we can inform you on how you were doing it incorrectly. – Kevin B Apr 29 '14 at 20:59
  • 1
    _"and `replace()` only replaces the first instance."_ - Did you look at any documentation for `.replace()`? [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) is a good place to look for all (built-in) JS functions...and it has [some examples](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Examples)... – nnnnnn Apr 29 '14 at 21:00
  • All of the answers so far are saying roughly the same thing. It seems very discourteous to downvote each of them without explanation. – HandyAndyShortStack Apr 29 '14 at 21:06
  • All of the answers are mediocre compared to the already accepted answer. http://stackoverflow.com/a/1144788/400654 – Kevin B Apr 29 '14 at 21:07
  • @KevinB - If we started downvoting all mediocre answers, there would be a lot of downvotes going around. – adeneo Apr 29 '14 at 21:11
  • Maybe, mediocre was the wrong word. duplicate maybe. The accepted answer was from 5 years ago. – Kevin B Apr 29 '14 at 21:14
  • @HandyAndyShortStack I didn't downvote them. :/ –  Apr 29 '14 at 21:16

1 Answers1

-1

You should use a global regex for the first argument to String.prototype.replace:

var s = "mississippi";
var newString = s.replace(/i/g, 'u');
console.log(newString); //=> 'mussuppuppu'