JavaScript - for 循环迭代不适用于 indexOf 函数

JavaScript - for loop Iterations not working with indexOf function

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);

如果没有 break 命令,这是一个无限循环。我不知道如何替换文本中的两个 World War II。我知道 indexOf 只处理第一个实例,但是,我如何遍历文本以使其处理 both/all 我想要替换的实例?除了使用字符串替换方法。

将字符串 replace() 与正则表达式一起使用,而不是 for 循环迭代。

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');