Case insensitive replace all

I am looking for any implementation of case insensitive replacing function. For example, it should work like this:

'This iS IIS'.replaceAll('is', 'as');

and result should be:

'Thas as Ias'

Any ideas?

UPDATE:

It would be great to use it with variable:

var searchStr = 'is';
'This iS IIS'.replaceAll(searchStr, 'as');
97181 次浏览

使用正则表达式。

'This iS IIS'.replace(/is/ig, 'as')

试试 regex:

'This iS IIS'.replace(/is/ig, 'as');

工作示例: http://jsfiddle.net/9xAse/

例如:
使用 RegExp 对象:

var searchMask = "is";
var regEx = new RegExp(searchMask, "ig");
var replaceMask = "as";


var result = 'This iS IIS'.replace(regEx, replaceMask);
String.prototype.replaceAll = function(strReplace, strWith) {
// See http://stackoverflow.com/a/3561711/556609
var esc = strReplace.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var reg = new RegExp(esc, 'ig');
return this.replace(reg, strWith);
};

这完全实现了您提供的示例。

'This iS IIS'.replaceAll('is', 'as');

报税表

'Thas as Ias'

当您使用正则表达式解决方案时,如果您的替换字符串包含例如“ ?”.所以你必须转义所有的正则表达式字符,或者使用例如:

String.replacei = String.prototype.replacei = function (rep, rby) {
var pos = this.toLowerCase().indexOf(rep.toLowerCase());
return pos == -1 ? this : this.substr(0, pos) + rby + this.substr(pos + rep.length);
};

这不会改变字符串中出现的所有“ is”。因此,可以在函数中编写 while 循环。

I recommend the Str _ iplace function from php.js, which even replaces strings from arrays.

这是保罗答案中的即兴发挥,在正则表达式和非正则表达式之间存在性能差距

用于比较的正则表达式代码是本杰明 · 弗莱明的回答。

JSPerf
Case-sensitive
Regex: 66,542 Operations/sec
非正则表达式: 178,636次操作/秒(拆分-连接)

不分大小写
Regex: 37,837 Operations/sec
非正则表达式: 12,566操作/秒(indexOf-subr)

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

注意,在上面提供的答案中有一个错误。如果您的原始字符串以替换开始,那么您将输入一个无限循环。

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);
if (pos == 0) break; // Fixes bug
pos--;
}
return strTemp;
}
};


// Example
var text = "Dog Jumps Over The Lazy Dog";
console.log(text.replaces("dog", "Cat", true));