我写了一个简单的'replaceAll'函数来扩展String.prototype。在IE9中有效的输出,但在IE7/IE8中未定义的输出
String.prototype.replaceAll = function (removalChar, insertionChar) {
var output = "";
for (var i = 0; i < this.length; i++) {
if(this[i] == removalChar) {
output += insertionChar;
}
else {
output += this[i];
}
}
return output;
}
测试代码:
var test = "Hello-1-2-3";
alert(test.replaceAll("-"," "));
我的测试代码提醒所有的浏览器IE9,包括Hello 1 2 3
。
但在IE7和8,输出我得到的是这样的:undefinedundefinedundefinedundefinedundefinedundefined...
的jsfiddle:http://jsfiddle.net/cd4Z2/ (试试这个在IE7/IE8)
怎么可能我可能重写函数以确保它在IE7/8上工作而不会破坏其他浏览器的行为?
感谢所有的超快速反应!我已经决定'接受'Saturnix的答案,因为它是最详细的答案,但是Teemu和那个孩子的答案也很酷! – SNag