admin管理员组文章数量:1134599
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');
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');
Share
Improve this question
edited Jul 4, 2019 at 9:19
Uwe Keim
40.7k61 gold badges185 silver badges302 bronze badges
asked Sep 5, 2011 at 22:55
Sergey MetlovSergey Metlov
26.3k28 gold badges96 silver badges154 bronze badges
9 Answers
Reset to default 220Try regex:
'This iS IIS'.replace(/is/ig, 'as');
Working Example: http://jsfiddle.net/9xAse/
e.g:
Using RegExp object:
var searchMask = "is";
var regEx = new RegExp(searchMask, "ig");
var replaceMask = "as";
var result = 'This iS IIS'.replace(regEx, replaceMask);
console.log(result);
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 implements exactly the example you provided.
'This iS IIS'.replaceAll('is', 'as');
Returns
'Thas as Ias'
When you use the regex solution you can get problems if your replace string contain e.g. "?". So you have to escape all regex characters or use e.g.:
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);
};
this will not change all the occurrences of 'is' in the string. Therefore you can write a while loop in the function.
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));
Note there is a bug in an answer provided above. If your original string starts with the replacement you'll enter an infinite loop.
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));
Use a regular expression.
'This iS IIS'.replace(/is/ig, 'as')
If you're looking for a way to avoid regular expressions due to performance concerns, you might consider implementing a custom function. This custom function can loop through the string, identify matches regardless of their case, and then replace them. But be aware that this approach might not be more performant than using a well-crafted regular expression, especially for large strings or complex replacement patterns.
function replaceCaseInsensitive(str, find, replace) {
let result = "";
let findLower = find.toLowerCase();
let index = 0;
while (index < str.length) {
if (str.substring(index).toLowerCase().startsWith(findLower)) {
result += replace;
index += find.length;
} else {
result += str[index];
index++;
}
}
return result;
}
// Example usage
let originalString = "Hello World";
let newString = replaceCaseInsensitive(originalString, "world", "Universe");
console.log(newString); // Output: Hello Universe
Insensitive ReplaceAll:
12 053 033 replaces by 1 sec
for ReplaceAll("Dog Jumps Over The Lazy Dog", "dog", "Cat")
Example:
function ReplaceAll(base,told,tnew) { // replace insensitive
if (told=="") {return base;}
var u=base.toLowerCase();
var t=told.toLowerCase();
var ss=""; var p=-1; var i=0;
p=u.indexOf(t);
if (p>-1) {
let mLen=told.length;
while (p>=0) {
ss+=base.substr(0,p)+tnew;
i=p+mLen;
base=base.substr(i);
u=u.substr(i);
p=u.indexOf(t);
}
ss+=base; //fix bug
return ss;
}
return base;
}
/*Test:
function loopThrough() {
for (let i = 0; i < 60000000; i++) {
let s=ReplaceAll("Dog Jumps Over The Lazy Dog","dog","Cat");
}
}
$(document).ready(function(){
$("button").click(function(){
//alert(ReplaceAll("Dog Jumps Over The Lazy Dog","dog", "Cat"));
document.getElementById("demo").innerHTML = '...';
let startTime = new Date();
loopThrough();
let endTime = new Date();
let timeElapsed = endTime - startTime;
document.getElementById("demo").innerHTML = "elapsed times: " + timeElapsed + " milliseconds.";
*/
I recommend the str_ireplace function from php.js, which even replaces strings from arrays.
本文标签: javascriptCase insensitive replace allStack Overflow
版权声明:本文标题:javascript - Case insensitive replace all - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736780307a1952557.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论