0

var text = "Uncle Bob was in World War II. Many people believe World War II was 
the most destructive war to date.";

var replace = text.indexOf("World War II");


for (var i = 0; i < text.length; i++) {
  if (replace[i] !== -1) {
    text = text.slice(0, replace) + "the second world war" +
      text.slice(replace + 12);
  }
  break;

}
alert(text);

Without the break command, this is an infinite loop. I cannot figure out how to replace both World War IIs in text. I understand indexOf only deals with the first instance, however, how can I iterate through text to make it deal with both/all instances of what I want to replace? Besides using string replace method.

BobRoss
  • 53
  • 1
  • 11
  • 1
    Not sure this is what you're really looking for, but just in case: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – Cypher Aug 20 '15 at 05:53
  • `indexOf()` finds the first occurrence. It does not find all occurrences. – Paul Aug 20 '15 at 05:54
  • Use text = text.replace(/World War II/g, 'the second world war'); If you want to just replace the all occurrences of text. – Kalpesh Patel Aug 20 '15 at 05:54
  • 1
    Use String.replace() with a regex – Arun P Johny Aug 20 '15 at 05:54
  • 1
    Duplicate of http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript – jozzy Aug 20 '15 at 05:56

1 Answers1

1

Use String replace() With a Regular Expression instead of for loop iteration.

var text = "Uncle Bob was in World War II. Many people believe World War II was the most destructive war to date.";
var str = text.replace(/World War II/g, 'the second world war');
napster
  • 349
  • 1
  • 4
  • 16
  • Thank you very much! The book I'm reading talks about changing the first instance of "world war II" to "the second world war", then in the next loop iteration, finding the next surviving instances of "world war II" and changing that. I was trying to figure that out but I suppose it's not as efficient and more difficult. – BobRoss Aug 20 '15 at 06:04