Yan Yan - 4 months ago 9
Javascript Question

Replace all using indexOf and while loop in String.prototype

I am trying to implement in my code this string replacement function:

String.prototype.replaceAll = function(f,r) {
if (f != r) {
while (this.indexOf(f) !== -1) {
this = this.replace(f,r);
}
} else {
return this;
}
};


And I already tried to use this:

String.prototype.replaceAll = function(f,r) {
return this.split(f).join(r);
};


But this last replacement function does not work with two or more characters in the search expression.

So I really need to use the first function with the while-loop.

Does anybody knows what is the problem in the first function showed?

Answer
function(f,r)
{
var str=this;
if (f != r) {
    while (str.indexOf(f) !== -1) {
       str=str.replace(f,r);
    }
}
return str.toString();
}