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只处理第一个实例,但是,如何迭代文本以使其处理我想要替换的所有实例?除了使用字符串替换方法。
答案 0 :(得分:1)
使用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');