Case insensitive replace all

Javascript

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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'

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

Solution 5 - Javascript

Use a regular expression.

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

Solution 6 - Javascript

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

Solution 7 - Javascript

I recommend the str_ireplace function from php.js, which even replaces strings from arrays.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSergey MetlovView Question on Stackoverflow
Solution 1 - JavascriptChanduView Answer on Stackoverflow
Solution 2 - JavascriptBenView Answer on Stackoverflow
Solution 3 - JavascriptPaulView Answer on Stackoverflow
Solution 4 - JavascriptStefansAryaView Answer on Stackoverflow
Solution 5 - JavascriptDaniel A. WhiteView Answer on Stackoverflow
Solution 6 - JavascriptPatrick SirrView Answer on Stackoverflow
Solution 7 - JavascriptandreszsView Answer on Stackoverflow