IT Share you

대소 문자를 구분하지 않고 모두 교체

shareyou 2020. 11. 19. 22:20
반응형

대소 문자를 구분하지 않고 모두 교체


대소 문자를 구분하지 않는 대체 기능의 구현을 찾고 있습니다. 예를 들어 다음과 같이 작동합니다.

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

결과는 다음과 같아야합니다.

'Thas as Ias'

어떤 아이디어?

최신 정보:

변수와 함께 사용하면 좋을 것입니다.

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

정규식을 시도하십시오.

'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 루프를 작성할 수 있습니다.


이것은 Paul의 대답에서 즉석에서 나온 것이며 Regex와 Non-regex 사이에 성능 차이가 있습니다.

비교를위한 정규식 코드는 Benjamin Fleming의 답변입니다.

JSPerf
대소 문자 구분
Regex : 66,542 Operations / sec
Non-Regex : 178,636 Operations / sec (split-join)


대소 문자 구분 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));


정규식을 사용하십시오.

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

배열의 문자열을 대체하는 php.js str_ireplace 함수를 권장합니다 .

참고 URL : https://stackoverflow.com/questions/7313395/case-insensitive-replace-all

반응형