[JavaScript] 문자열

Jun·2022년 5월 1일

JavaScript

목록 보기
6/13
post-thumbnail

학습 목표

  • length 속성을 활용해 문자열의 길이를 확인할 수 있다.
  • 두 개 이상의 문자열을 하나의 문자열로 만들 수 있다.
  • slice() 메서드를 활용해 문자열을 원하는 만큼 ‘복사’할 수 있다.
  • 영문으로 된 문자열을 대문자 또는 소문자로 바꿀 수 있다.
  • 문자열 중 원하는 문자의 index를 찾고 접근할 수 있다
  • str.indexOf('a') 또는 str.lastIndexOf('a') , str[1]
  • includes() 메서드를 활용해 문자열 중 원하는 문자가 포함되어 있는지 알 수 있다. str.includes('a')
  • split() , join() 메서드를 활용해 문자열을 배열로 바꾸거나, 배열을 문자열로 바꿀 수 있다.
  • 템플릿 리터럴(Template literals) 문법을 사용할 수 있다.

문자열(string)이란?

모든 글자의 나열. 코드와 구분하기 위해 작은따옴표(')나 큰따옴표(")를 사용한다.
문자 하나는 character 이며, char 이라는 축약어로 부르기도 한다.

  1. 문자열 접근 (accessing a character)
  • str[index] 로 접근이 가능하다. 재할당은 불가능하다.(read-only)
let str = 'Hello';
console.log(str[0]) // output : 'H'
console.log(str[4]) // output : 'o'
console.log(str[10]) // output : undefined
str[0] = 'Z';
conosle.log(str) // output : 'Hello' not 'Zello'
  1. 문자열의 연결 (concatenating strings)
  • + 연산자를 쓸 수 있다.
  • string 타입과 다른 타입 사이에 + 연산자를 쓰면, string 형식으로 변환된다. ( toString )
  • str1.concat(str2, str3...); 의 형태로도 사용 가능하다.
let str1 = 'Hello, ';
let str2 = 'World!';
let str3 = '1';
console.log(str1+str2); // output : 'Hello, World!'
console.log(str3 + 7); // output : '17'
console.log(str3 + [1,2,3]); // output: '11,2,3'
  1. 문자열의 속성(property) : length
  • 문자열의 전체 길이를 반환한다.
let str = '0123456789';
console.log(str.length); // output : 10

문자열의 메소드(method)

  1. str.indexOf(searchValue)
  • argumens : 찾고자 하는 문자열
  • return value: 처음으로 일치하는 index, 찾고자 하는 문자열이 없으면 -1 반환.
  • lastIndexOf는 문자열 뒤에서부터 찾음.
'Blue Whale'.indexOf('Blue'); // output : 0
'Blue Whale'.indexOf('blue'); // output : -1
'Blue Whale'.indexOf('Whale'); // output : 5
'Blue Whale Whale'.indexOf('Whale'); // output : 5

'canal'.lastIndexOf('a'); // output : 3
  1. str.includes(searchValue)
  • 찾고자 하는 문자열이 str에 있는지 판별한다. boolean 타입을 반환한다.
  • Internet Explorer와 같은 구형 브라우저에서는 작동하지 않으므로 주의!
'Apple, Banana'.includes('Apple'); // output : true
'Apple, Banana'.includes('grape'); // output : false
  1. str.split(seperator)
  • arguments : 분리 기준이 될 문자열
  • return value : 분리된 문자열이 포함된 배열
let str = 'Hello my name is Jun'
console.log(str.split(' '));
// output : ['Hello', 'from', 'the', 'other', 'side']

let str2 = '12345'
console.log(str.split(''); // output : ['1', '2', '3', '4', '5']
  • csv 형식을 처리할 때 유용

csv (comma-sepearted values)
몇 가지 필드를 쉼표로 구분한 텍스트 데이터 및 텍스트 파일이다.

  1. str.substring(start, end)
  • arguments : 시작 index, 끝 index
  • return value : 시작과 끝 index 사이의 문자열
let str = '0123456789';
console.log(str.substring(0,3)); // output : '012'
console.log(str.substring(3,0)); // output : '012'
console.log(str.substring(1,4)); // output : '123'
console.log(str.substring(-1,4)); // output : '0123', 음수는 0으로 취급한다.
console.log(str.substring(0,20)); // output : '0123456789', index 범위 초과
  1. str.toLowerCase() / str.toUpperCase()
  • arguments : 없음
  • return value : 대, 소문자로 변환된 문자열
consoel.log('ALPHABET'.toLowerCase()); // output : 'alphabet'
console.log('alpahbet'.toUpperCase()); // output : 'ALPHABET'
  1. str.trim()
  • arguments : 없음
  • return value : 양 끝의 공백이 제거된 문자열
console.log('   Hello   '.trim()); // output : 'Hello'
console.log('World        '.trim()); // output : 'World'
console.log('Jun'.trim()); // output : 'Jun'
  1. str.join()
  • arguments : 없음
  • return value : 배열의 모든 요소를 연결한 하나의 문자열
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join()); // output: "Fire,Air,Water"
console.log(elements.join(''));// output: "FireAirWater"
console.log(elements.join('-'));// output: "Fire-Air-Water"

템플릿 리터럴 (template literals)

내장된 표현식을 허용하는 문자열 리터럴이다. 여러 줄로 이뤄진 문자열과 문자 보간기능을 사용할 수 있다. ''"" 대신에 `` (백틱)을 사용한다.

let name = 'Jun'
console.log(`Hello, my name is ${name}!`);
// output : 'Hello, my name is Jun!'
profile
FrontEnd Engineer를 목표로 공부합니다.

0개의 댓글