LearningJavaScript
4. 문자열 다루기
jyshimmy
2020. 7. 28. 15:11
정의
Accessing a character using index numbers
**문자열에 index로 접근은 가능하지만 쓸 수는 없다 (read-only기능만 있음)
var str = 'CodeStates';
console.log(str[0]); // 'C'
conosle.log(str[10]); // undefined
str[0] = 'G';
console.log(str); //'Codestates' not 'GodeStates'
Concatenating strings
문자열에 + 연산자를 사용해 다른 타입도 문자열 형식으로 변환할 수 있다 (toString)
var str1 = 'Code';
var str2 = 'States';
var str3 = '1';
console.log(str1 + str2); // 'CodeStates'
console.log(str3 + 7); // '17'
//str1.concat(str2, str3...);의 형태로 사용할 수도 있음
Length property of a string
배열, 문자열에 속한 속성
var str = 'CodeStates';
console.log(str.length); // 10
String Methods (all immutable)
**unlike some array methods all string methods are immutable, meaning "원본 불변".
1. indexOf
- str.indexOf(searchValue) 앞에서부터
- lastIndexOf(searchValue) 뒤에서부터
2. includes
- boolean값(true 또는 false)을 리턴함
3. split
- str.split(separator)
- arguments: 분리 기준이 될 문자열
- return value: 분리된 문자열이 포함된 배열; 공백(' ')을 이용해 잘라냄.
var str = 'Hello from the other side';
console.log(str.split(' '));
//['Hello', 'from', 'the', 'other', 'side']
**csv(comma-separated values)형식을 처리할 떄 유용한 편;
공백을 넘어, 줄바꿈이 있는 경우: csv.split('\n')
<문자열 다루기> 동영상 강의 11:00 쯤
4. substring
- str.substring(start, end)
- arguments: 시작 index, 끝 index (사실 순서는 둘이 바뀌어도 무관)
- return value: 시작과 끝 index 사이의 문자열
var str = 'abcdefghij';
console.log(str.substring(0, 3)); // 'abc'
console.log(str.substring(3, 0)); // 'abc'; argument순서가 바뀌어도 변하는 건 없음
console.log(str.substring(1, 4)); // 'bcd'
console.log(str.substring(-1, 4)); // 'abcd' 음수는 0으로 취급
console.log(str.substirng(0, 20)); // 'abcdefghij', index범위를 초과하면 마지막 index취급
5. slice
slice vs. substring
slice | ||
6. toLowerCase, toUpperCase
str.toLowerCase() / str.toUpperCase()
- arguments:없음
- return value: 대, 소문자로 변환된 문자열
7. trim
8. 공백 문자(탭 문자 (\t), carriage return (\r\n) 및 return 문자 (\n)
9. match (advanced)
10. replace (advanced)
11. 정규 표현식 (advanced)