개발/Javascript

[JS] 문자열 비교하기

hayeonn 2022. 9. 24. 21:43
반응형

자바스크립트에는 다양한 문자열 비교 방법이 있다.

동등연산자로 문자열이 동등한지 비교하거나 문자열의 크기를 비교할 수 있다.

 

1. 동등 연산자 (==, ===)로 문자열 비교

두 개의 문자열이 같은지 다른지 확인할 때 사용한다.

두 문자열이 같으면 'true' 다르면 'false' 리턴한다.

const str1 = 'hello';
const str2 = 'hello';
const str3 = 'world';

console.log(str1 === str2); // true
console.log(str1 === str3); // false
console.log(str2 === str3); // false

console.log(str1 == str2); // true
console.log(str1 == str3); // false
console.log(str2 == str3); // false

 

2. 문자열 크기(대소) 비교 : 비교 연산자 ('>' , '<') 

'>' , '<' 연산자를 사용해 문자열 순서를 비교할 수 있다.

- '>' , '<' 연산자는 문자열을 '사전 순서' 대로 비교해 결과를 리턴한다.

- 문자열의 ASCII 값을 비교해 리턴한다. 

console.log('apple' > 'banana'); // false
console.log('apple' > 'abcd');   // true
console.log('apple' > 'a');      // true
console.log('apple' > 'Banana'); // true
console.log('apple' > '1');      // true

1.   

'apple'과 'banana'의 사전 순서는 'banana'가 더 뒤여서 'apple'은 'banana'보다 작다.

'a'의 ASCII 값은 97 이고 'b'의 ASCII 값은 98 이다.

따라서 'apple' < 'banana'

 

2. 

'apple'과 'abcd'의 첫번 째 글자인 'a'의 ASCII 값은 97이다.

'apple'의 두번째 글자인 'p'의 ASCII 값은 112 이고 'abcd'의 두번째 글자인 'b'의 ASCII 값은 97이다.

따라서 'abcd' < 'apple'

 

3.

'apple'과 'a'의 첫번 째 글자인 'a'의 ASCII 값은 97 이다.

'apple'의 두번째 글자인 'p'의 ASCII 값은 112 이고 'a'의 두번째 글자는 없어 0으로 비교된다.

따라서 'a' < 'apple'

 

4. 

'apple''의 첫번 째 글자인 'a'의 ASCII 값은 97이다.

'Banana'의 첫번 째 글자인 대문자 'B'의 ASCII 값은 66 이다.

따라서 'Banana' < 'apple'

 

5. 

'apple'의 첫번 째 글자인 'a'의 ASCII 값은 97이다.

'1'의 ASCII 값은 49 이다.

따라서 '1' < 'apple'

 

 

[ASCII값]

- 숫자 0 ~ 10 : 48 ~ 57

- 알파벳 대문자 A ~ Z : 65 ~ 90

- 알파벳 소문자 a ~ z : 97 ~ 122 

 

나머지 ASCII 값 : https://en.wikipedia.org/wiki/ASCII#Printable_characters

 

ASCII - Wikipedia

From Wikipedia, the free encyclopedia Jump to navigation Jump to search American character encoding standard ASCII ( ASS-kee),[3]: 6  abbreviated from American Standard Code for Information Interchange, is a character encoding standard for electronic c

en.wikipedia.org

 

[출처]

https://hianna.tistory.com/374

 

[Javascript] 문자열 비교하기 (동등 비교, 대소 비교)

 동등 연산자('==', '===') 비교 Javascript에서 문자열의 비교를 위해서는 동등연산자('==' 또는 '===')를 사용합니다. 동등 연사자를 사용하여 두 개의 문자열을 비교해서 두 문자열이 같으면 'true'를

hianna.tistory.com

https://codechacha.com/ko/javascript-compare-strings/

 

JavaScript - 문자열 비교 방법, 5가지

자바스크립트에서 다양한 문자열 비교 방법 5가지를 소개합니다. 동등 연산자(==, ===)로 문자열이 동등한지 비교하거나, >, < 연산자로 문자열의 크기 비교할 수 있습니다. 또는 includes(), indexOf()로

codechacha.com