32장 String
32.1 String 생성자 함수
- String객체는 생성자 함수로, new연산자와 함께 호출하여 String인스턴스 생성 가능
- 문자열은 배열처럼 인덱스를 사용해서 각 문자에 접근할 수 있음
- 문자열은 원시값이므로 변경할수 없음
32.2 length프로퍼티
- length프로퍼티는 문자열의 문자 개수를 반환함
32.3 String메서드
32.3.1 String.prototype.indexOf
- indexOf메서드는 대상 문자열에서 인수로 전달받은 문자열을 검색하여 첫 번째 인덱스 반환, 없으면 -1반환
- 2번째 인수로 검색을 시작할 인덱스를 전달할 수 있음
str.indexOf('l');
str.indexOf('l', 3);
32.3.2 String.prototype.search
- search메서드는 대상 문자열에서 인수로 전달받은 정규표현식과 매치하는 문자열을 검색하여 일치하는 문자열의 인덱스를 반환, 없으면 -1반환
str.search(/o/);
32.3.3 String.prototype.includes (ES6)
- includes메서드는 대상 문자열에 인수로 전달받은 문자열이 포함되어 있는지 확인하여 true/false로 반환함
- 2번째 인수로 검색을 시작할 인덱스 전달 가능
str.includes('Hello');
str.includes('l', 3);
32.3.4 String.prototype.startsWith (ES6)
- startsWith메서드는 대상 문자열이 인수로 전달받은 문자열로 시작하는지 확인하여 그 결과를 true/false로 반환함
str.startWith('He');
32.3.5 String.prototype.endsWith (ES6)
- endsWith메서드는 대상 문자열이 인수로 전달받은 문자열로 끝나는지 확인하여 그 결과를 true/false로 반환함
- 2번째 인수로 검색할 문자열의 길이를 전달할 수 있음
str.endsWith('ld');
str.endsWith('lo', 5);
32.3.6 String.prototype.chatAt
- chatAt메서드는 대상 문자열에서 인수로 전달받은 인덱스에 위치한 문자를 검색하여 반환함
- 인덱스가 문자열의 범위를 벗어난 정수일 경우 빈 문자열 반환
str.charAt(1);
32.3.7 String.prototype.substring
- substring메서드는 대상 문자열에서 첫 번째 인수 인덱스부터 두 번째 인수 인덱스 이전 문자까지의 부분 문자열 반환함
- 2번째 인수는 생략가능(생략하면 마지막 문자열까지 반환)
str.substring(1, 4);
- indexOf메서드와 함께 사용하면 특정 문자열 기준으로 앞뒤에 위치한 부분 문자열을 취득할 수 있음
const str = 'Hello World';
// 스페이스 기준으로 앞에 있는 부분 문자열 취득
str.substring(0, str.indexOf(' ')); // -> 'Hello'
// 스페이스 기준으로 뒤에 있는 부분 문자열 취득
str.substring(str.indexOf(' ') + 1, str.length); // -> 'World'
32.3.8 String.prototype.slice
- slice메서드는 substring메서드와 동일하게 동작함
- 인수에 음수를 전달하면 대상 문자열 가장 뒤에서부터 문자열을 잘라내어 반환함
const str = 'hello world';
str.slice(0, 5) // -> 'hello'
str.slice(-5) // -> 'world'
32.3.9 String.prototype.toUpperCase
- toUpperCase메서드는 대상 문자열을 모두 대문자로 변경하여 반환함
str.toUpperCase();
32.3.10 String.prototype.toLowerCase
- toLowerCase메서드는 대상 문자열을 모두 소문자로 변경한 문자열을 반환함
str.toLowerCase();
32.3.11 String.prototype.trim
- trim메서드는 대상 문자열 앞뒤에 공백이 있을 경우 제거한 문자열을 반환함
const str = ' foo ';
str.trim(); // -> 'foo'
32.3.12 String.prototype.repeat (ES6)
- repeat메서드는 대상 문자열을 인수로 전달받은 정수만큼 반복해서 새로운 문자열 반환
- 인수가 0이면 빈문자열을 반환함
const str = 'abc';
str.repeat(2); // -> 'abcabc'
32.3.13 String.prototype.replace
- replace메서드는 첫번째 인수를 검색하여 두번째 인수로 바꾼 문자열을 반환함
- 첫번째로 검색된 문자열만 변경함
const str = 'Hello world';
str.replace('world', 'Lee'); // -> 'Hello Lee'
const str = 'Hello Hello';
str.replace(/hello/gi, 'Lee'); // -> 'Lee Lee'
32.3.14 String.prototype.split
- split메서드는 인수를 검색하여 분리된 문자열을 배열로 반환함
- 인수를 생략하면 문자열을 모두 분리해서 반환함
- 두번째 인수로 배열의 길이를 정할 수 있음
const str = 'How are you doing?';
str.split(' '); // -> ["How", "are", "you", "doing?"]