어떻게 수행합니까 대소문자 무시 문자열 비교 JavaScript 에서?
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
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'));
끝 - < 스니핏 >;!
이 ' {감도: # 39, & # 39 accent&. } '알' () '같은 기본 서신입니다 로카레콤파레 치료를 위해 서로 다른 두 가지 유형이 같은 unless 같이 3 예) 등이 있습니다.
' {감도 사용할 수도 있습니다. # 39, & # 39 base&. 기본 캐릭터는 '에서는 2}, 이는 그들의 문자를 deltamove avamer 같은 (그래서' A '와' & # 약간만이라도 취급되고 225; ').
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' 플래깅.
https://stackoverflow.com/questions/177719/javascript-case-insensitive-search
모두 때 비교되는 문장열 변수가 아닌 상수입니다) 한 후, 조금 더 복잡한 & # 39, it& # 39 의 경우 정규 표현식 생성해야 합니다 그러나 문자열에서 반군지역 에서 문자열을 string regex 는 정규 표현식 구성자를 경우 발생할 수 있습니다 잘못된 일치시킵니다 일치시킵니다 특수 문자 또는 실패했습니다. 항목이없습니다.
즉, 케이스 () 는 특정 작업을 로케일에. 테이크 댓 인되며 빠르시니라 책정안 따라 할 수 있습니다 예를 들어, 두 명의 이름이 비교할 경우 고려해야 할 수도 있습니다 로케일에서만 UUID 값을 비교하여 머시닝할 같은 경우 이 같은 기능을 사용하여 생성된 후 내가 왜 내 유틸리티인 라이브러리란 않을 수 있습니다. (단, 성능 향상을 위해 유형 검사를 포함되어 있지 않은 이유).
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;
}
['구체화하십시오 로카르콤파레'] (https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/string/localecompare) 는 최근 의견을 따라 기도하였나니 대소문자 무시 비교 (그밖에 다른 강력한 창조하셨노).
'xyz'.localeCompare('XyZ', undefined, { sensitivity: 'base' }); // returns 0
그리고 일반 기능을 사용할 수 있습니다
function equalsIgnoringCase(text, other) {
return text.localeCompare(other, undefined, { sensitivity: 'base' }) === 0;
}
참고로 정의되지 않은 '대신' 특정 로케일에 입력하십시오. 아마 작업할 수 있습니다. 이는 로 매든 docs 에 못지않게 중요한
>. 스웨덴의, & # 228. 그리고 개별적입니다 기본 문자
As of time, UC 브라우저를 인터넷 없는 안드로이드, 오페라 미니 지원 및 options locale 매개변수입니다. # 검색 (https://caniuse.com/) = 로카레콤파레 dbasyb 최신임 대한 정보.
나는 최근에 만든 초소형 제공하는 문자열 라이브러리 알고 구분하지 않습니다. https://github.com/nickuraltsev/ignore-case. ('' 토퍼케이스 내부적으로 사용한다.)
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
염려되는 경우 방향을 비항등 (아마도 운영까지도 정렬하려면 목록) 유니코드 문자를 경우 변환 너회가 꽤-많은 등 해야 할 가능성이 훨씬 더 많다 소문자화 대문자화 토로르카스 최고의 변환 사용할 수 있습니다.
function my_strcasecmp( a, b )
{
if((a+'').toLowerCase() > (b+'').toLowerCase()) return 1
if((a+'').toLowerCase() < (b+'').toLowerCase()) return -1
return 0
}
자바스크립트를 사용하여, C" " 로케일에 것으로 보인다. 그 결과 오더할 는 문자열 비교 그 이외의 문장열 ASCII 문자를 포함할 수 있는 경우. # 39 의 there& 대한 점검 작업을 수행할 수 있는 별로 없는 훨씬 더 상세한 써줬지
예를 들어, 문자열 변수를 문자열 변수를 짚단 싶다 '' 바늘 '를'. 세 가지 정보:
(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
}
[1]: =, = JavaScript% 2fguide% 2fregular_expressions 러디어스슬루크 en-US& 러디어스트로계 https://developer.mozilla.org/en-us/docs/web/javascript/guide/regular_expressions?
두 가지 방법으로 대소문자 무시 비교:
List. " search"; 문자열 검색 방법을 대소문자를 구분하지 않습니다. 문자열 검색 및 기타 검토완료 메서드을 http://support. 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>
여기에 대답을 토대로 추가 연장할 수 있지만, 내가 좋아하는 많은 솔루션 구체화하십시오 lib:
String.prototype.equalIgnoreCase = function(str)
{
return (str != null
&& typeof str === 'string'
&& this.toUpperCase() === str.toUpperCase());
}
그냥 이렇게 it like you do 자바 가상 머신 (jvm) 에 사용할 수 있습니다!
예:
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"
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
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");
}
끝 - < 스니핏 >;!
str = 'Lol', str2 = 'lOl', regex = new RegExp('^' + str + '$', 'i');
if (regex.test(str)) {
console.log("true");
}
모두 같은 경우 문자열은 http://upload. 로케일과 '린트레비콜라터' 이렇게 객체에는 사용할 수 있습니다.
function equalIgnoreCase(s1: string, s2: string) {
return new Intl.Collator("en-US", { sensitivity: "base" }).compare(s1, s2) === 0;
}
분명히 캐시하려면 병합기 '이' 효율성 향상을 위해 할 수 있습니다.
이러한 방식을 사용하는 것보다 훨씬 빨리 정규 표현식 장점을 기반으로 한다는 것, 이는 매우 커스터마이징됩니다 (http://otl. '설명' 와 '옵션' 구성자를 매개변수입니다 로켈을 이 글에서 위) 의 설정되었습니다 코레 이타 즉시 사용 가능.
심지어 이 질문은 이미 답변됨. 나는 다른 접근 방식을 사용하여 정규 표현식 및 해당되어서는 무시하려면 대 / 소문자를 구분합니다. 내 링크를 참조하시기 바랍니다
$("#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);
}
Regex 사용하는 문자열 일치 또는 비교.
'매치 ()' 는 문자열 비교, JavaScript 에서 사용할 수 있습니다.
예:
var matchString = "Test";
if (matchString.match(/test/i)) {
alert('String matched');
}
else {
alert('String not matched');
}
간단한 코드를 사용하기 위한 ',' 스니핏 제공하는 확실히요 오토메이티드 없으므로 정규 표현식 here& # 39 의 내 시도.
function compareInsensitive(str1, str2){
return typeof str1 === 'string' &&
typeof str2 === 'string' &&
new RegExp("^" + str1.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "$", "i").test(str2);
}
여러 가지 장점을 갖고 있다.
Regex 를 사용하지 않고 예외 발생 느린 것은 어떨까?
return str1 != null && str2 != null
&& typeof str1 === 'string' && typeof str2 === 'string'
&& str1.toUpperCase() === str2.toUpperCase();
스케쳐내 일치시키려면 nulll / 정의되지 않은 후:
return (str1 == null && str2 == null)
|| (str1 != null && str2 != null
&& typeof str1 === 'string' && typeof str2 === 'string'
&& str1.toUpperCase() === str2.toUpperCase());
만약 대한 몇 가지 이유로 신경습니까 정의되지 않은 vs nulll:
return (str1 === undefined && str2 === undefined)
|| (str1 === null && str2 === null)
|| (str1 != null && str2 != null
&& typeof str1 === 'string' && typeof str2 === 'string'
&& str1.toUpperCase() === str2.toUpperCase());
이 오류는 의 향상된 버전인 이 오토메이티드.
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();
}
}
< br/>; < hr/>;
<! - begin 스니핏: js 숨기십시오: 진정한 콘솔: 진정한 바벨. > 거짓값 -;
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);
끝 - < 스니핏 >;!