[JavaScript] 문자열(string)의 속성과 매서드

iberis2·2022년 12월 16일
0

📜 .length : 문자열의 길이를 확인

💡 공백도 길이에 포함

console.log('안녕하세요'.length);   // 5
console.log('안녕 나비야'.length);  // 6

//[참고] '안녕 나비야'[2] 2번째 인덱스는 공백

📜 숫자형 문자열은 계산 가능

💡덧셈은 문자열로 계산되므로 주의

console.log('2' * 2);   // 4
console.log('2' + 2);   // 22
let stringNum = '2' + 2;
console.log(typeof(stringNum));  //string

📜 문자열 주요 메서드

  • .toLowerCase() : 문자열을 소문자로 변경
  • .toUpperCase() : 문자열을 대문자로 변경
  • .concat() : 문자열 연결 연산자 + 처럼 문자열을 이어붙일 수 있음
  • .indexOf(item) : item 문자가 문자열 안에 몇 번째 인덱스인지
    동일한 문자는 먼저 나오는 문자의 인덱스 반환
  • .lastIndexOf(item) : item을 뒤에서부터 찾아서 인덱스 반환
  • .slice(num) : 문자열의 일부를 자를 수 있음
  • .trim() : 시작과 끝의 공백 제거
※편의상 console.log 생략

'HELLO WORLD'.toLowerCase() // 'hello world'
'hello world'.toUpperCase() // 'HELLO WORLD'
'hello '.concat('world') // 'hello world'
'hello world'.indexOf('o') // 4
'hello world'.lastIndexOf('o') // 7
'hello world'.slice(0, 5) // 'hello'
'hello world'.slice(3) // 'lo world'
'  hello world  '.trim() // 'hello world'

📜 .indexOf() : 문자열 내에 특정 문자의 위치 확인

💡찾는 문자가 2개 이상일 경우, 가장 앞에 있는 문자의 인덱스를 조회

💡포함되어 있지 않으면 -1 을 반환

※편의상 console.log 생략

'🍎🍓🍉🍇'.indexOf('🍎');   // 0
'🍎🍓🍉🍇'.indexOf('🖥');   // -1
'최초의 JavaScript는 Netscape의 Brendan Eich에 의해 만들었다.'.indexOf('Eich');  // 34
'최초의 JavaScript는 Netscape의 Brendan Eich에 의해 만들었다.'.indexOf('Dahl');  // -1

📜 .includes() : 문자열 내에 특정 문자가 포함되어 있는지 확인

※편의상 console.log 생략

'🍎🍓🍉🍇'.includes('🍎'); // true
'🍎🍓🍉🍇'.includes('🖥'); // false
'최초의 JavaScript는 Netscape의 Brendan Eich에 의해 만들었다.'.includes('Eich'); // true
'최초의 JavaScript는 Netscape의 Brendan Eich에 의해 만들었다.'.includes('Dahl'); // false
profile
React, Next.js, TypeScript 로 개발 중인 프론트엔드 개발자

0개의 댓글