String

5o_hyun·2022년 2월 23일
0
post-thumbnail

표준 빌트인 객체 String은 원시타입인 문자열을 다룰 때 유용한 프로퍼티와 메서드를 제공한다.

String 생성자함수

표준 빌트인 객체 String 객체는 생성자 함수 객체다. 따라서 new연산자로 String 인스턴스를 생성할 수 있다.

const strObj = new String('kim');
console.log(strObj);
// String {0: "k", 1: "i", 2: "m", constructor: Object}

String 객체는 배열과 마찬가지로 length 프로퍼티와 인덱스를 나타내는 문자열을 프로퍼티키로, 각 문자를 프로퍼티 값으로 갖는 유사 배열 객체이면서 이터러블이다.

따라서 length 프로퍼티를 갖는다.
또한 length가 있으므로 인덱스를 갖는다.

const strObj = new String('kim');
console.log(strObj.length); // 3

String 메서드

배열에서는 원본배열을 직접 변경하는 메서드와 새로운 배열을 반환하는 메서드가 있다.
하지만 String메서드는 언제나 새로운 문자열을 반환한다.

1. String.prototype.indexOf

.indexOf 메서드는 몇번째에 있는 인덱스인지 알려준다.

const str = 'hello';
console.log(str.indexOf('o')); // 4

2. String.prototype.includes

.includes메서드는 인수로 전달받은 문자열이 있으면 true 없으면 false를 반환한다.

const str = 'hello';
console.log(str.includes('o')); // true
console.log(str.includes('a')); // false

3. String.prototype.startsWith

.startsWith메서드는 인수로 전달받은 문자열로 시작하는지 확인하여 true나 false로 반환한다.

const str = 'hello';
console.log(str.startsWith('h')); // true

4. String.prototype.charAt

charAt메서드는 인수로 전달받은 인덱스에 접근하여 인덱스에 위치한 문자를 검색해 반환한다.

const str = 'hello';

for(var i = 0; i < str.length; i++){
  console.log(str.charAt(i)); // h e l l o
}

5. String.prototype.substring

.substring메서드는 첫번째 인수로 전달받은 인덱스에 위치하는 문자부터 두번째 인수로 전달받은 인덱스에 위치하는 문자의 바로 이전문자 ( -1 ) 까지 반환한다.
slice랑 비슷한 것 같다.

const str = 'hello';
console.log(str.substring(1,3)); // el

6. String.prototype.slice

.slice메서드는 substring메서드와 동일하게 동작한다.
단, slice 메서드에는 음수인 인수를 전달할 수 있다. 음수인 인수를 전달하면 대상 문자열의 가장 뒤에서부터 시작하여 문자열을 잘라내어 반환한다.

const str = 'hello';
console.log(str.slice(-3)); // llo

7. String.prototype.toUpperCase

.toUpperCase메서드는 대문자로 바꿔준다.

const str = 'hello';
console.log(str.toUpperCase()); // HELLO

8. String.prototype.toLowerCase

.toLowerCase메서드는 소문자로 바꿔준다.

const str = 'Hello';
console.log(str.toLowerCase()); // hello

9. String.prototype.trim

.trim메서드는 공백, 띄어쓰기를 제거해준다.
주로 검색 창 등을 만들 때 쓰인다.

const str = '        hello        ';
console.log(str.trim()); // hello <-- 공백없음

10. String.prototype.replace

.replace메서드는 첫번째 인수로 전달받은 문자열을 검색하여 두번째 인수로 전달한 문자열로 치환한 문자열을 반환한다.

const str = 'hello world';
// 첫번째인수 world를 검색해 두번째인수인 sohyun으로 지환
console.log(str.replace('world','sohyun')); // hello sohyun

11. String.prototype.split

.split메서드는 넘겨주는 인자를 기준으로 잘라서 배열로 반환한다.

const str = 'how are you doing?';
// 공백으로 단어구분하기
console.log(str.split(' ')); // ["how", "are", "you", "doing?"]

// 빈문자열을 인수로 전달하면 각 문자를 모두 반환 (공백포함)
console.log(str.split('')); // ["h", "o", "w", " ", "a", "r", "e", " ", "y", "o", …]
profile
학생 점심 좀 차려

0개의 댓글