0

I wrote a simple 'replaceAll' function that extends String.prototype.

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

Test code:

var test = "Hello-1-2-3";
alert(test.replaceAll("-"," "));


My test code alerts Hello 1 2 3 in all browsers including IE9.

But in IE7 and 8, the output I get is something like this: undefinedundefinedundefinedundefinedundefinedundefined...


jsFiddle: http://jsfiddle.net/cd4Z2/ (try this in IE7/IE8)


How could I possibly rewrite the function to ensure it works on IE7/8 without breaking its behaviour on other browsers?

SNag
  • 17,681
  • 10
  • 54
  • 69
  • Thanks for all the super-quick responses! I've decided to 'accept' Saturnix's answer for being the most detailed, but Teemu's and wiz kid's answers are pretty cool too! – SNag Nov 21 '13 at 12:12

3 Answers3

3

You can't access string chars with this[i] in IE7/8. Use .charAt(i) instead, as explained here:

Javascript strings - getting the char at a certain point


Updated fiddle (tested in IE8): http://jsfiddle.net/cd4Z2/2/

I've just replaced this[i] with this.charAt(i).


In this question, some good reasons are stated on why you'd prefer to use charAt as opposed to string[index]. The latter is not part of ECMAScript 3.

Community
  • 1
  • 1
Saturnix
  • 10,130
  • 17
  • 64
  • 120
2

IE<9 don't treat a string like an array, i.e. they lack ability to refer individual letter with index. You can use a temporary array (var temp = this.split('');) instead of this[i]

Teemu
  • 22,918
  • 7
  • 53
  • 106
2

Try this out:-

String.prototype.replaceAll = function (removalChar, insertionChar) {
    var output = "";
    var res = this.split('');
    for (var i = 0; i < this.length; i++) {
        if(res[i] == removalChar) {
            output += insertionChar;
        }
        else {
            output += res[i];
        }
    }
    return output;
}


var test = "Hello-1-2-3";
//alert(test.replace("-"," "));
alert(test.replaceAll("-"," "));
Aditya Singh
  • 9,512
  • 5
  • 32
  • 55