티스토리 뷰

32장. String

  • 원시 타입인 문자열을 다룰 때 유용한 프로퍼티와 메서드를 제공한다.

32-1. String 생성자 함수

  • String 생성자 함수에 인수를 전달하지 않고 new 연산자와 함께 호출하면 [[StringData]] 내부 슬롯에 빈 문자열을 할당한 String 래퍼 객체를 생성한다.
  • 문자열은 원시 값이므로 변경 불가
  • 문자열이 아닌 값을 전달하면 문자열로 강제 변환한 후 [[StringData]] 내부 슬롯에 변환된 문자열을 할당한 String 래퍼 객체를 생성한다.
const strObj = new String();
console.log(strObj); // String { length: 0, [[PrimitiveValue]]: "" }

const strObj = new String('Lee');
console.log(strObj); // String {0: "L", 1: "e", 2: "e", length: 3, [[PrimitiveValue]]: "Lee" }

const strObj = new String(123);
console.log(strObj); // String {0: "1", 1: "2", 2: "3", length: 3, [[PrimitiveValue]]: "123" }

const strObj = new String(null);
console.log(strObj); // String {0: "n", 1: "u", 2: "l", 3: "l", length: 4, [[PrimitiveValue]]: "null" }

// 형변환
String(1); // '1'
String(NaN); // 'NaN'
String(Infinity); // 'Infinity'

String(true); // 'true'
String(false); // 'false'

32-2. length 프로퍼티

  • String 래퍼 객체는 유사 배열 객체다.
'Hello'.length; // 5
'Bye'.length; // 3

33-3. String 메서드

  • String 객체의 메서드는 언제나 새로운 문자열을 반환한다.
  • 문자열은 immutable한 원시값이기에 String 래퍼 객체도 읽기전용 객체로 제공된다.

String.prototype.indexOf

  • 인수로 전달받은 문자열을 검색하여 첫 번째 인덱스 반환, 실패시 -1 반환
const str = 'Hello World';
str.indexOf('l'); // 2
str.indexOf('or'); // 7
str.indexOf('x'); // -1

// 검색을 시작할 인덱스 지정
str.indexOf('l', 3); // 3

// 검색할 문자열이 존재하는지 확인할 때
if (str.indexOf('Hello') === -1)
if (str.inclues('Hello'))

String.prototype.search

  • 인수로 전달받은 정규 표현식과 매치하는 문자열을 검색하여 일치하는 인덱스 반환, 실패시 -1 반환
const str = 'Hello World';
str.search(/o/); // 4
str.search(/x/); // -1

String.prototype.inclues

  • 포함하고 있는지 확인, boolean 반환
const str = 'Hello World';
str.includes('Hello'); // true
str.includes('xxx'); // false

// 검색을 시작할 인덱스 지정
str.includes('l', 3); // true

String.prototype.startsWith

  • 인수로 전달받은 문자열로 시작하는지 확인하여 boolean 반환
  • 2번째 인수로 검색을 시작 할 인덱스 지정 가능

String.prototype.endWith

  • 인수로 전달받은 문자열로 끝나는지 확인하여 boolean 반환
const str = 'Hello World';
str.endsWith('ld'); // true

// str의 처음부터 5자리까지 ('Hello')가 'lo'로 끝나는지 확인
str.endsWith('lo', 5); // true

String.prototype.charAt

  • 인수로 전달받은 인덱스에 위치한 문자 반환
const str = 'Hello World';
str.charAt(0); // H
str.charAt(5); // ''

String.prototype.substring

  • 첫 번째 인수로 전달받은 인덱스에 위치하는 문자부터 두 번째 인수로 전달받은 인덱스에 위치하는 문자의 바로 이전 문자까지의 부분 문자열 반환
const str = 'Hello World';
str.substring(1, 4); // 'ell'
str.substring(1); // 'ello World'

// 첫 번째 인수 > 두 번째 인수인 경우 두 인수 교환됨.
str.substring(4, 1); // 'ell'

// 인수 < 0 또는 NaN인 경우 0으로 취급됨.
str.substring(-2); // 'Hello World'

// 인수 > 문자열의 길이 인 경우 문자열의 길이로 취급됨.
str.substring(1, 100); // 'ello World'
str.substring(20); // ''

String.prototype.slice

  • substring과 동일하게 동작한다. 단, slice 메서드에는 음수인 인수를 전달할 수 있다.
const str = 'Hello World';

str.slice(0, 5); // 'Hello'
str.slice(2); // 'llo world'
str.slice(-5); // 'world'

String.prototype.toUpperCase, toLowerCase

const str = 'Hello World';

str.toUpperCase(); // 'HELLO WORLD'
str.toLowerCase(); // 'hello world'

String.prototype.trim

  • 앞 뒤 공백 문자 제거한 문자열 반환
const str = '  foo  ';
str.trim(); // 'foo'

str.trimStart(); // 'foo  '
str.trimEnd(); // '  foo'

str.replace(/\\s/g, ''); // 'foo'
str.replace(/^\\s+/g, ''); // 'foo  '
str.replace(/\\s+$/g, ''); // '  foo'

String.prototype.repeat

const str = 'abc';

str.repeat(); // ''
str.repeat(0); // ''
str.repeat(1); // 'abc'
str.repeat(2); // 'abcabc'
str.repeat(-1); // RangeError: Invalid count value

String.prototype.replace

const str = 'Hello World';
str.replace('World', 'Lee'); // 'Hello Lee'

const str = 'Hello world world';
str.replace('world', 'Lee'); // 'Hello Lee world'

const str = 'Hello Hello';
str.replace(/hello/gi, 'Lee'); // 'Lee Lee'

String.prototype.split

const str = 'How are you doing?';

str.split(' '); // ['How', 'are', 'you', 'doing?']

str.split(/\\s/); // ['How', 'are', 'you', 'doing?']

str.split(''); // ['H', 'o', ... '?']

str.split(); // ['How are you doing?']

str.split(' ', 3); // ['How', 'are', 'you']

' > 모던 자바스크립트 딥다이브' 카테고리의 다른 글

33장. 7번째 데이터 타입 Symbol  (0) 2022.07.10
34장. 이터러블  (2) 2022.07.08
30장. Date  (2) 2022.06.12
29장. Math  (0) 2022.06.12
28장. Number  (0) 2022.06.12