etc./StackOverFlow

대소문자를 구분하지 않는 문자열 비교를 수행하는 방법은 무엇입니까?

청렴결백한 만능 재주꾼 2023. 4. 25. 10:56
반응형

질문자 :flybywire


JavaScript에서 대소문자를 구분하지 않는 문자열 비교를 수행하려면 어떻게 합니까?



가장 간단한 방법은(특수 유니코드 문자가 걱정되지 않는 경우) toUpperCase 를 호출하는 것입니다.

 var areEqual = string1.toUpperCase() === string2.toUpperCase();

SLaks

편집 : 이 답변은 원래 9년 전에 추가되었습니다. sensitivity: 'accent' 옵션과 함께 localeCompare 를 사용해야 합니다.

 function ciEquals(a, b) { return typeof a === 'string' && typeof b === 'string' ? a.localeCompare(b, undefined, { sensitivity: 'accent' }) === 0 : a === b; } console.log("'a' = 'a'?", ciEquals('a', 'a')); console.log("'AaA' = 'aAa'?", ciEquals('AaA', 'aAa')); console.log("'a' = 'á'?", ciEquals('a', 'á')); console.log("'a' = 'b'?", ciEquals('a', 'b'));

{ sensitivity: 'accent' } 는 위의 세 번째 예에서와 같이 다른 액센트가 없는 한 동일한 기본 문자의 두 가지 변형을 동일하게 처리하도록 localeCompare()

{ sensitivity: 'base' } 사용할 수 있습니다. 이는 기본 문자가 동일한 한 두 문자를 동등하게 취급합니다(따라서 A á 와 동등하게 취급됨).

의 세 번째 매개 변수 있습니다 localeCompare IE10에서 지원 또는 낮추거나 당신이 그 브라우저를 지원해야하는 경우, 당신은 대체 어떤 종류의가 필요합니다 그래서 특정 모바일 브라우저 (위에 링크 된 페이지의 호환성 차트를 참조)되지 않습니다

 function ciEqualsInner(a, b) { return a.localeCompare(b, undefined, { sensitivity: 'accent' }) === 0; } function ciEquals(a, b) { if (typeof a !== 'string' || typeof b !== 'string') { return a === b; } // v--- feature detection return ciEqualsInner('A', 'a') ? ciEqualsInner(a, b) : /* fallback approach here */; }

원래 답변

JavaScript에서 대소문자를 구분하지 않는 비교를 수행하는 가장 좋은 방법 i match() 메서드를 사용하는 것입니다.

대소문자를 구분하지 않는 검색

비교되는 두 문자열이 상수가 아닌 변수인 경우 문자열에서 RegExp를 생성해야 하지만 문자열을 RegExp 생성자에 전달하면 문자열에 특수 정규식이 있는 경우 일치하지 않거나 일치하지 않을 수 있으므로 조금 더 복잡합니다. 그 안의 캐릭터들.

국제화에 관심이 있다면 toLowerCase() 또는 toUpperCase() 를 사용하지 마십시오. 모든 언어에서 정확한 대소문자 구분 비교를 제공하지 않기 때문입니다.

http://www.i18nguy.com/unicode/turkish-i18n.html


Samuel Neff

최근 의견에서 말했듯이 string::localeCompare 는 대소문자를 구분하지 않는 비교를 지원합니다(다른 강력한 기능 중에서).

다음은 간단한 예입니다.

 'xyz'.localeCompare('XyZ', undefined, { sensitivity: 'base' }); // returns 0

사용할 수 있는 일반 기능

 function equalsIgnoringCase(text, other) { return text.localeCompare(other, undefined, { sensitivity: 'base' }) === 0; }

undefined 대신 작업 중인 특정 로케일을 입력해야 합니다. 이것은 MDN 문서에 표시된 것처럼 중요합니다.

스웨덴어에서 ä 및 a는 별도의 기본 문자입니다.

감도 옵션

MDN에서 표로 만든 감도 옵션

브라우저 지원

게시 당시 Android 및 Opera Mini용 UC 브라우저는 로케일옵션 매개변수를 지원 하지 않습니다. 최신 정보는 https://caniuse.com/#search=localeCompare 를 확인하십시오.


Jay Wick

업데이트:

의견에 따라 소스에 대한 이전 답변 검사 source contains keyword 있어 동일성 검사가 ^$ 추가되었습니다.

 (/^keyword$/i).test(source)

정규 표현식의 도움으로 우리도 달성할 수 있습니다.

 (/keyword/i).test(source)

/i 는 대소문자를 무시합니다. 필요하지 않은 경우 다음과 같이 대소문자를 구분하지 않는 일치 항목을 무시하고 테스트할 수 있습니다.

 (/keyword/).test(source)

SP007

대소문자 구분은 로케일별 작업임을 기억하십시오. 시나리오에 따라 이를 고려할 수 있습니다. 예를 들어, 두 사람의 이름을 비교하는 경우 로케일을 고려할 수 있지만 UUID와 같은 시스템 생성 값을 비교하는 경우에는 그렇지 않을 수 있습니다. 이것이 내가 utils 라이브러리에서 다음 기능을 사용하는 이유입니다(유형 검사는 성능상의 이유로 포함되지 않음).

 function compareStrings (string1, string2, ignoreCase, useLocale) { if (ignoreCase) { if (useLocale) { string1 = string1.toLocaleLowerCase(); string2 = string2.toLocaleLowerCase(); } else { string1 = string1.toLowerCase(); string2 = string2.toLowerCase(); } } return string1 === string2; }

Shital Shah

불평등의 방향이 걱정된다면(아마도 목록을 정렬하고 싶을 때) 대소문자 변환을 해야 하고 유니코드에 대문자보다 소문자가 더 많기 때문에 toLowerCase를 사용하는 것이 가장 좋은 변환일 것입니다.

 function my_strcasecmp( a, b ) { if((a+'').toLowerCase() > (b+'').toLowerCase()) return 1 if((a+'').toLowerCase() < (b+'').toLowerCase()) return -1 return 0 }

Javascript는 문자열 비교에 로케일 "C"를 사용하는 것 같으므로 문자열에 ASCII 문자가 아닌 다른 문자가 포함되어 있으면 결과 순서가 추악합니다. 문자열을 훨씬 더 자세히 검사하지 않고는 이에 대해 할 수 있는 일이 많지 않습니다.


Jasen

저는 최근에 대소문자를 구분하지 않는 문자열 도우미를 제공하는 마이크로 라이브러리를 만들었습니다: https://github.com/nickuraltsev/ignore-case . (내부적으로 toUpperCase 사용합니다.)

 var ignoreCase = require('ignore-case'); ignoreCase.equals('FOO', 'Foo'); // => true ignoreCase.startsWith('foobar', 'FOO'); // => true ignoreCase.endsWith('foobar', 'BaR'); // => true ignoreCase.includes('AbCd', 'c'); // => true ignoreCase.indexOf('AbCd', 'c'); // => 2

Nick Uraltsev

문자열 변수 haystack needle 을 찾고 싶다고 가정합니다. 세 가지 문제가 있습니다.

  1. 국제화된 애플리케이션은 string.toUpperCasestring.toLowerCase 피해야 합니다. 대신 대소문자를 무시하는 정규식을 사용하십시오. 예를 들어, var needleRegExp = new RegExp(needle, "i"); 그 다음은 needleRegExp.test(haystack) 입니다.
  2. needle 의 값을 모를 수 있습니다. needle 정규식 특수 문자가 포함되지 않도록 주의하십시오. needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); .
  3. 다른 경우에, 대소문자를 무시하고 needlehaystack 을 정확하게 일치시키려면 정규 표현식 생성자의 시작 부분에 "^" "$"

요점 (1)과 (2)를 고려하면 다음과 같은 예가 될 수 있습니다.

 var haystack = "A. BAIL. Of. Hay."; var needle = "bail."; var needleRegExp = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i"); var result = needleRegExp.test(haystack); if (result) { // Your code here }

Chris Chute

여기에 많은 답변이 있지만 String lib 확장을 기반으로 솔루션을 추가하고 싶습니다.

 String.prototype.equalIgnoreCase = function(str) { return (str != null && typeof str === 'string' && this.toUpperCase() === str.toUpperCase()); }

이 방법을 사용하면 Java에서와 같이 사용할 수 있습니다!

예시:

 var a = "hello"; var b = "HeLLo"; var c = "world"; if (a.equalIgnoreCase(b)) { document.write("a == b"); } if (a.equalIgnoreCase(c)) { document.write("a == c"); } if (!b.equalIgnoreCase(c)) { document.write("b != c"); }

출력은 다음과 같습니다.

 "a == b" "b != c" 

 String.prototype.equalIgnoreCase = function(str) { return (str != null && typeof str === 'string' && this.toUpperCase() === str.toUpperCase()); } var a = "hello"; var b = "HeLLo"; var c = "world"; if (a.equalIgnoreCase(b)) { document.write("a == b"); document.write("<br>"); } if (a.equalIgnoreCase(c)) { document.write("a == c"); } if (!b.equalIgnoreCase(c)) { document.write("b != c"); }


Nebulosar

문자열 일치 또는 비교에 RegEx를 사용합니다.

match() 를 사용할 수 있습니다. RegEx i 를 넣는 것을 잊지 마십시오.

예시:

 var matchString = "Test"; if (matchString.match(/test/i)) { alert('String matched'); } else { alert('String not matched'); }

Om Prakash Sharma

대소문자를 구분하지 않는 비교에는 두 가지 방법이 있습니다.

  1. 문자열을 대문자로 변환한 다음 엄격 연산자( === )를 사용하여 비교합니다. 엄격한 연산자가 피연산자를 다루는 방법: http://www.thesstech.com/javascript/relational-logical-operators
  2. 문자열 메서드를 사용한 패턴 일치:

대소문자를 구분하지 않는 검색을 위해 "검색" 문자열 방법을 사용하십시오. 검색 및 기타 문자열 방법에 대해 읽어보십시오. http://www.thesstech.com/pattern-matching-using-string-methods

 <!doctype html> <html> <head> <script> // 1st way var a = "apple"; var b = "APPLE"; if (a.toUpperCase() === b.toUpperCase()) { alert("equal"); } //2nd way var a = " Null and void"; document.write(a.search(/null/i)); </script> </head> </html>

Sohail Arif

이 질문에도 이미 답이 나와 있습니다. RegExp를 사용하고 대소문자를 구분하지 않도록 일치하는 다른 접근 방식이 있습니다. 내 링크를 참조하십시오 https://jsfiddle.net/marchdave/7v8bd7dq/27/

 $("#btnGuess").click(guessWord); function guessWord() { var letter = $("#guessLetter").val(); var word = 'ABC'; var pattern = RegExp(letter, 'gi'); // pattern: /a/gi var result = word.match(pattern); alert('Ignore case sensitive:' + result); }

David S Lee

str = 'Lol', str2 = 'lOl', regex = new RegExp('^' + str + '$', 'i'); if (regex.test(str)) { console.log("true"); }

Parth Raval

두 문자열의 알려진 로캘이 동일한 경우 다음과 같이 Intl.Collator

 function equalIgnoreCase(s1: string, s2: string) { return new Intl.Collator("en-US", { sensitivity: "base" }).compare(s1, s2) === 0; }

분명히 더 나은 효율성을 위해 Collator 를 캐시할 수 있습니다.

이 접근 방식의 장점은 RegExp를 사용하는 것보다 훨씬 더 빨라야 하고 바로 localesoptions 생성자 매개변수에 대한 설명 참조).


Alexander Abakumov

확장자를 썼습니다. 아주 사소한

 if (typeof String.prototype.isEqual!= 'function') { String.prototype.isEqual = function (str){ return this.toUpperCase()==str.toUpperCase(); }; }

Jhankar Mahbub

나는 이 빠른 속기 변형을 좋아한다 -

 export const equalsIgnoreCase = (str1, str2) => { return (!str1 && !str2) || (str1 && str2 && str1.toUpperCase() == str2.toUpperCase()) }

처리 속도가 빠르고 의도한 대로 수행합니다.


Neetesh Dadwariya

예외를 던지지 않고 느린 정규식을 사용하지 않는 것은 어떻습니까?

 return str1 != null && str2 != null && typeof str1 === 'string' && typeof str2 === 'string' && str1.toUpperCase() === str2.toUpperCase();

위의 스니펫은 문자열이 null이거나 정의되지 않은 경우 일치시키고 싶지 않다고 가정합니다.

null/undefined를 일치시키려면 다음을 수행하십시오.

 return (str1 == null && str2 == null) || (str1 != null && str2 != null && typeof str1 === 'string' && typeof str2 === 'string' && str1.toUpperCase() === str2.toUpperCase());

어떤 이유로 정의되지 않은 대 null에 관심이 있는 경우:

 return (str1 === undefined && str2 === undefined) || (str1 === null && str2 === null) || (str1 != null && str2 != null && typeof str1 === 'string' && typeof str2 === 'string' && str1.toUpperCase() === str2.toUpperCase());

Ben Wilde

RegExp 사용을 위한 간단한 코드 스니펫을 명확하게 제공한 답변이 없기 때문에 여기에 제 시도가 있습니다.

 function compareInsensitive(str1, str2){ return typeof str1 === 'string' && typeof str2 === 'string' && new RegExp("^" + str1.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "$", "i").test(str2); }

몇 가지 장점이 있습니다.

  1. 매개변수 유형을 확인합니다( undefined str1.toUpperCase() 와 같은 표현식을 충돌시킵니다).
  2. 가능한 국제화 문제를 겪지 않습니다.
  3. RegExp 문자열을 이스케이프합니다.

Ohad Schneider

ascii 텍스트를 다루고 있다는 것을 알고 있다면 대문자/소문자 오프셋 비교를 사용할 수 있습니다.

"완벽한" 문자열(일치하려는 문자열)이 소문자인지 확인하십시오.

 const CHARS_IN_BETWEEN = 32; const LAST_UPPERCASE_CHAR = 90; // Z function strMatchesIgnoreCase(lowercaseMatch, value) { let i = 0, matches = lowercaseMatch.length === value.length; while (matches && i < lowercaseMatch.length) { const a = lowercaseMatch.charCodeAt(i); const A = a - CHARS_IN_BETWEEN; const b = value.charCodeAt(i); const B = b + ((b > LAST_UPPERCASE_CHAR) ? -CHARS_IN_BETWEEN : CHARS_IN_BETWEEN); matches = a === b // lowerA === b || A === b // upperA == b || a === B // lowerA == ~b || A === B; // upperA == ~b i++; } return matches; }

matsko

더 나은 브라우저 호환성을 위해 정규식에 의존할 수 있습니다. 이것은 지난 20년 동안 출시된 모든 웹 브라우저에서 작동합니다.

 String.prototype.equalsci = function(s) { var regexp = RegExp("^"+this.replace(/[.\\+*?\[\^\]$(){}=!<>|:-]/g, "\\$&")+"$", "i"); return regexp.test(s); } "PERSON@Ü.EXAMPLE.COM".equalsci("person@ü.example.com")// returns true

이것은 모든 사용자가 최신 웹 브라우저를 사용하지 않는다는 점을 고려하기 때문에 여기에서 찾은 다른 답변과 다릅니다.

참고: 터키어와 같은 특이한 경우를 지원해야 하는 경우 i와 I는 터키어에서 같은 문자가 아니기 때문에 localeCompare를 사용해야 합니다.

 "I".localeCompare("i", undefined, { sensitivity:"accent"})===0// returns true "I".localeCompare("i", "tr", { sensitivity:"accent"})===0// returns false

PHP Guru

이것은 이 답변 의 개선된 버전 입니다.

 String.equal = function (s1, s2, ignoreCase, useLocale) { if (s1 == null || s2 == null) return false; if (!ignoreCase) { if (s1.length !== s2.length) return false; return s1 === s2; } if (useLocale) { if (useLocale.length) return s1.toLocaleLowerCase(useLocale) === s2.toLocaleLowerCase(useLocale) else return s1.toLocaleLowerCase() === s2.toLocaleLowerCase() } else { if (s1.length !== s2.length) return false; return s1.toLowerCase() === s2.toLowerCase(); } }



사용법 및 테스트:

 String.equal = function (s1, s2, ignoreCase, useLocale) { if (s1 == null || s2 == null) return false; if (!ignoreCase) { if (s1.length !== s2.length) return false; return s1 === s2; } if (useLocale) { if (useLocale.length) return s1.toLocaleLowerCase(useLocale) === s2.toLocaleLowerCase(useLocale) else return s1.toLocaleLowerCase() === s2.toLocaleLowerCase() } else { if (s1.length !== s2.length) return false; return s1.toLowerCase() === s2.toLowerCase(); } } // If you don't mind extending the prototype. String.prototype.equal = function(string2, ignoreCase, useLocale) { return String.equal(this.valueOf(), string2, ignoreCase, useLocale); } // ------------------ TESTS ---------------------- console.log("Tests..."); console.log('Case sensitive 1'); var result = "Abc123".equal("Abc123"); console.assert(result === true); console.log('Case sensitive 2'); result = "aBC123".equal("Abc123"); console.assert(result === false); console.log('Ignore case'); result = "AbC123".equal("aBc123", true); console.assert(result === true); console.log('Ignore case + Current locale'); result = "AbC123".equal("aBc123", true); console.assert(result === true); console.log('Turkish test 1 (ignore case, en-US)'); result = "IiiI".equal("ıiİI", true, "en-US"); console.assert(result === false); console.log('Turkish test 2 (ignore case, tr-TR)'); result = "IiiI".equal("ıiİI", true, "tr-TR"); console.assert(result === true); console.log('Turkish test 3 (case sensitive, tr-TR)'); result = "IiiI".equal("ıiİI", false, "tr-TR"); console.assert(result === false); console.log('null-test-1'); result = "AAA".equal(null); console.assert(result === false); console.log('null-test-2'); result = String.equal(null, "BBB"); console.assert(result === false); console.log('null-test-3'); result = String.equal(null, null); console.assert(result === false);


Sergey

둘 다 더 낮은 값으로 변환하고(성능상의 이유로 한 번만) 한 줄에서 삼항 연산자와 비교합니다.

 function strcasecmp(s1,s2){ s1=(s1+'').toLowerCase(); s2=(s2+'').toLowerCase(); return s1>s2?1:(s1<s2?-1:0); }

Luca C.

ASCII를 사용하여 이 작업을 수행할 수도 있습니다.

 function toLower(a){ let c = ""; for(let i = 0;i<a.length;i++){ let f = a.charCodeAt(i); if(f < 95){ c += String.fromCharCode(f+32); } else{ c += a[i]; } } return c; } function compareIt(a,b){ return toLower(a)==toLower(b); } console.log(compareIt("An ExamPlE" , "an example"));

Erfan Taghvaei

출처 : http:www.stackoverflow.com/questions/2140627/how-to-do-case-insensitive-string-comparison

반응형