TIL 53 | 위코드 사전스터디4 : JS(String)

YB.J·2021년 7월 27일
0

wecode_사전스터디

목록 보기
5/22
post-thumbnail

위코드 사전스터디 과정 중 JavaScript의 String(문자열)에 대해서 정리해본다

String

String(문자열)이란?

  • 대부분은 문자(영어, 한글 등)는 String으로 사용 가능
  • 홑따옴표, 쌍따옴표, 백틱으로 문자를 감싸서 String으로 사용한다
  • 공백(띄어쓰기)도 문자열로 인식한다
  • 변수를 선언한 뒤, 문자열을 할당해서 사용할 수 있다
let greeting = 'Hello world'
let myName = 'Code Kim'

console.log(greeting); // Hello world 출력
console.log(myName); // Code Kim 출력

+연산자로 문자열 합치기

  • 문자열을 '+' 연산자(문자열 연결 연산자)를 사용하여 서로 합칠 수 있다
console.log('Hello world'+' '+'Code Kim'); // Hello world Code Kim
console.log(greeting+' '+myName); // Hello world Code Kim 
  • 특이점 : 숫자열과 문자열을 합치면 문자가 된다!!
console.log(2+2); // 4 (typeof Number)
console.log(22); // 22 (typeof Number)
console.log('2'+'2'); // 22 (typeof String)
console.log(2+"2"); // 22 (typeof String) > 숫자와 문자를 합치면 문자

🎶 더하기 지식!
문자열 연결 연산자(+연산자)는 피연산자 중 하나 이상이 문자열인 경우 문자열 연결 연산자로 동작한다. 그 외의 경우는 산술 연산자로 동작한다.
'1'+2; // '12'(문자)
1+'2'; // '12'(문자)
1+2; // 3(숫자)

문자열의 총 길이(length) 구하기

  • 'Hello world' : 총 길이는 11(공백도 문자열이기 때문에 길이 1개 포함된다)
  • 메서드로 구하는 방법이 있다(.length)
  • 활용 예시
const myString = 'Hello! wecode!!';
console.log(myString); // Hello! wecode!!

변수 myString의 길이를 구하고 싶을 때
console.log(myString.length); // 15

변수가 아니어도 된다
console.log('Hello! wecode!!'.length); // 15
  • console.log()안에서 구분자를 사용하여 다양하게 활용이 가능하다
  • 활용 예시
console.log(
  'Hello! wecode!! is ',
  'Hello! wecode!! is '.length);// Hello! wecode!! is 15
  • console.log()안에서 +연산자(문자열 연결 연산자)를 사용하여 다양하게 활용이 가능하다
console.log('Hello! wecode!! is '+'Hello! wecode!! is '.length); //
Hello! wecode!! is15
  • 구분자를 사용해서 출력한 것과 +연산자를 사용해서 출력한 결과는 다르다 > 구분자를 사용한 것은 Stiring+number로 출력, +연산자로 출력한 것은 전체 문자열로 출력된 것이다
profile
♪(^∇^*) 워-후!!(^∀^*)ノシ

0개의 댓글