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.

5
  • 1
    Not sure this is what you're really looking for, but just in case: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Aug 20, 2015 at 5:53
  • indexOf() finds the first occurrence. It does not find all occurrences. Commented Aug 20, 2015 at 5:54
  • Use text = text.replace(/World War II/g, 'the second world war'); If you want to just replace the all occurrences of text. Commented Aug 20, 2015 at 5:54
  • 1
    Use String.replace() with a regex Commented Aug 20, 2015 at 5:54
  • 1
    Duplicate of stackoverflow.com/questions/1144783/… Commented Aug 20, 2015 at 5:56

1 Answer 1

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');
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.