String.ReplaceAll function in JavaScript
The string functions in JavaScript string object does not have a method to replace all string found in a string. To replace all string pattern found in a string we need to write our own script.
The below script will help us doing that.
function ReplaceAll(Source,stringToFind,stringToReplace){
var temp = Source;
var index = temp.indexOf(stringToFind);
while(index != -1){
temp = temp.replace(stringToFind,stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
}
To call this function similar to an inbuilt function, we need to define the ReplaceAll function protype. Refer the below script,
String.prototype.ReplaceAll = function(stringToFind,stringToReplace){
var temp = this;
var index = temp.indexOf(stringToFind);
while(index != -1){
temp = temp.replace(stringToFind,stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
}
To call this function,
function replacecall()
{
var name = "I Love Dotnet";
alert(name);
alert(name.ReplaceAll(" ","_"));
}
|