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命令,这是一个无限循环。我无法弄清楚如何用文字替换两次世界大战。我了解indexOf仅处理第一个实例,但是,如何遍历文本以使其处理要替换的两个/所有实例?除了使用字符串替换方法。

最佳答案

使用带正则表达式的String 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');

关于javascript - JavaScript-for循环迭代不适用于indexOf函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32110453/

10-09 23:55
查看更多