반응형

 

 

 

 

 

 

 

 

📌 자바스크립트 대소 문자를 구분하지 않는 문자열 비교

 

자바스크립트에서 일반적으로 문자열을 비교할 때 대/소 문자를 구분하여 비교하지만,

대소 문자 구분 없이 문자열을 비교하는 방법은 다음과 같다.

  • toUpperCase(), toLowerCase() 메소드를 사용
  • localeCompare() 메소드를 사용
  • 정규 표현식을 통해 대소 문자를 구분하지 않는 비교 수행

 

 

 

 

1️⃣ toUpperCase( ), toLowerCase( )

toUpperCase( ) 는 문자열을 대문자로 변환하며, 변환 후 두 개의 문자열이 같은지 비교하면 된다.

var stringA = "This is a JavaScript tutorial";
var stringB = "THIS is A javascript TUTORIAL";

if (stringA.toUpperCase() === stringB.toUpperCase()){
    alert("The strings are equal.")
} else {
    alert("The strings are NOT equal.")
}

// The strings are equal.

 

toLowercase( ) 는 문자열을 소문자로 변환하며, 변환 후 두 개의 문자열이 같은지 비교하면 된다.

var stringA = "This is a JavaScript tutorial";
var stringB = "THIS is A javascript TUTORIAL";

if (stringA.toUpperCase() === stringB.toUpperCase()){
    alert("The strings are equal.")
} else {
    alert("The strings are NOT equal.")
}

// The strings are equal.

 

 

toLowercase( )는 일부 언어의 경우 소문자로 변환되지 않는 경우도 있기 때문에 toUpperCase( )이 선호된다.

 

 

 

 

 

2️⃣ localeCompare( )

localeCompare( ) 는 인수로 지정된 문자열이 정렬상 기준 문자열의 문자열 뒤에 있으면 음수, 그 반대의 경우는 양수, 동등한 경우에는 0을 반환한다.

// 기본 형식
string.localeCompare(compareString[, locale[, options]])

// 활용
if( 'javascript'.localeCompare('JavaScrpt', undefined, { sensitivity: 'base' }) == 0){
alert("The strings are equal")
} else{
alert("The strings are different.")
}

// The strings are different.

 

 

localeCompare( ) 레퍼런스

 

 

 

 

 

3️⃣ 정규식

const strA = 'This is a case sensitive comparison';
const strB = 'This is a CASE SENSITIVE comparison';
const regex = new RegExp(strA, "gi");
const comparison = regex.test(strB)

if(comparison) {
    alert('Similar strings');
} else {
    alert('Different strings');
}

// Similar strings

 

 

 

 

 

 

 

 

⚡ 참고사이트

https://www.delftstack.com/ko/howto/javascript/how-to-perform-case-insensitive-string-comparisons-in-javascript/

 

 

 

 

 

반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기