Web/JavaScript
[JavaScript] 모던 자바스크립트 Deep Dive 32장 - String
어징베
2023. 2. 3. 18:08

1. String 생성자 함수
표준 빌트인 객체인 String 객체는 생성자 함수 객체다.
String 생성자 함수에 인수를 전달하지 않고 new 연산자와 함께 호출하면 [[StringData]] 내부 슬롯에 빈 문자열을 할당항 String 래퍼 객체를 생성한다. String 래퍼 객체는 유사 배열 객체다.
const strObj = new String();
console.log(srtObj); // String {length: 0, [[PrimitiveValue]]: ""}
래퍼 객체: 문자열, 숫자, 불리언 값에 대해 객체처럼 접근하면 생성되는 임시 객체(원시값은 객체가 아니므로 프로퍼티나 메서드를 가질수 없음)
PrimitiveValue: 접근할 수 없는 프로퍼티
String 생성자 함수의 인수로 문자열 전달
const strObj = new String('Lee');
console.log(strObj);
// String {0: "L", 1: "e", 2: "e", length: 3, [[PrimitiveValue]]: "Lee"}
2. length 프로퍼티
'Hello'.length; // 5
'안녕하세요!'.length; // 6
3. String 메서드
String 객체의 메서드는 언제나 새로운 문자열을 반환한다.
문자열은 변경 불가능한 원시 값이기 때문에 String 래퍼 객체도 읽기 전용 객체로 제공된다.
const str = 'Hello World';
// indexOf
console.log(str.indexOf('l')); // 2
console.log(str.indexOf('l', 3)); // 2
console.log(str.indexOf('x')); // -1
// includes
console.log(str.includes('Hello')); // true
console.log(str.includes('x')); // false
// startsWith(대상 문자열이 인수로 전달받은 문자열로 시작하는지 확인)
console.log(str.startsWith('He')); // true
console.log(str.startsWith('x')); // false
// endsWith
console.log(str.endsWith('He')); // true
console.log(str.endsWith('x')); // false
// charAt
console.log(str.charAt(0)); // H
console.log(str.charAt(11)); // ""
// substring
console.log(str.substring(1, 4)); // ell
console.log(str.substring(1)); // ello World
// slice
console.log(str.substring(-5)); // Hello World, NaN인 경우 0으로 취급
console.log(str.slice(-5)); // World, 뒤에서 5자리 반환
// toUpperCase
console.log(str.toUpperCase()); // HELLO WORLD
// toLowerCase
console.log(str.toLowerCase()); // hello world
// trim
// 문자열 앞뒤 공백제거
// repeat
console.log(str.repeat(2)); // Hello WorldHello World
// replace
console.log(str.replace('Hello', 'Lee')); // Lee World
// split
console.log(str.split(' ')); // [ 'Hello', 'World' ]