🌻 문자열(
string
)이 무엇일까? 우리가 평소에 보던 그 책에 쓰여있는 글자를 문자열이라고 한다. 다만 컴퓨터는, 모두 글자로 되어있는 코드를 읽어야 하기 때문에 구분하기 위해서 '나 "을 사용하여 문자열을 구분한다.
length
라는 속성을 활용해 길이를 확인할 수 있다. str.length
str[1]
word1 + " " + word2
str.substring(0, 3)
str.toUpperCase
str.toLowerCase
str.indexOf('a')
str.includes('a')
str[index]
let str = 'CodeStates';
console.log(str[0]); // 'C'
console.log(str[4]); // 'S'
console.log(str[10]); // undefined
index
로 접근은 가능하지만 쓸 수는 없음 (read-only
)str[0] = 'G';
console.log(str); // 'CodeStates'
-> not 'GodeStates'
+
연산자를 쓸 수 있다.string
타입과 다른 타입 사이에 +
연산자를 쓰면, string
형식으로 변환 (toString
)let str1 = 'Code';
let str2 = "States";
let str3 = '1';
console.log(str1 + str2); // 'CodeStates'
console.log(str3 + 7); // '17'
str1.concat(str2, str3...);
의 형태로도 사용 가능let str = 'nayce';
console.log(str.length); // 5
arguments
: 찾고자 하는 문자열return value
: 처음으로 일치하는 index
, 찾고자 하는 문자열이 없으면 -1
lastIndexOf
는 문자열 뒤에서 부터 찾음'Blue Whale'.indexOf('Blue'); // 0
'Blue Whale'.indexOf('blue'); // -1
'Blue Whale'.indexOf('Whale'); // 5
'Blue Whale Whale'.indexOf('Whale'); // 5
'canal'.lastIndexOf('a'); // 3
str.includes(searchValue)
arguments
: 분리 기준이 될 문자열return value
: 분리된 문자열이 포함된 배열let str = 'Hello from the other side';
console.log(str.split(' '));
// ['Hello', 'from', 'the', 'other', 'side']
arguments
: 시작 index
, 끝 index
return value
: 시작과 끝 index
사이의 문자열let str = 'abcdefghij';
console.log(str.substring(0, 3)); // 'abc'
console.log(str.substring(3, 0)); // 'abc'
console.log(str.substring(1, 4)); // 'bcd'
console.log(str.substring(-1, 4)); // 'abcd', 음수는 0으로 취급
console.log(str.substring(0, 20)); // 'abcdefghij', index 범위를 넘을 경우 마지막 index로 취급
str.slice(start, end)
arguments
: 없음return value
: 대,소문자로 변환된 문자열console.log('ALPHABET'.toLowerCase()); // 'alphabet'
console.log('alphabet'.toUpperCase()); // 'ALPHABET'
string method
는 immutable
array method
는 immutable
및 mutable
여부를 잘 기억해야 함