This is the improvisation from Paul's answer, and there are a performance gap between Regex vs Non-regex
The regex code for comparation is taken Benjamin Fleming's answer..
JSPerf
Case-sensitive
Regex: 66,542 Operations/sec
Non-Regex: 178,636 Operations/sec (split - join)
Incase-sensitive
Regex: 37,837 Operations/sec
Non-Regex: 12,566 Operations/sec (indexOf - substr)
String.prototype.replaces = function(str, replace, incaseSensitive) {
if(!incaseSensitive){
return this.split(str).join(replace);
} else {
// Replace this part with regex for more performance
var strLower = this.toLowerCase();
var findLower = String(str).toLowerCase();
var strTemp = this.toString();
var pos = strLower.length;
while((pos = strLower.lastIndexOf(findLower, pos)) != -1){
strTemp = strTemp.substr(0, pos) + replace + strTemp.substr(pos + findLower.length);
pos--;
}
return strTemp;
}
};
// Example
var text = "A Quick Dog Jumps Over The Lazy Dog";
console.log(text.replaces("dog", "Cat", true));