[모던자바스크립트] 32장 - String

Yongwoo Cho·2021년 12월 9일
0

TIL

목록 보기
48/98
post-thumbnail

String 메서드

String 객체에는 원본 String 래퍼 객체(String 메서드를 호출한 String 래퍼 객체)를 직접 변경하는 메서드는 존재하지 않는다. 즉, String 객체의 메서드는 언제나 새로운 문자열을 반환한다. 문자열은 변경 불가능한 원시 값이기 때문에 String 래퍼 객체도 읽기 전용 객체로 제공된다.

String.prototype.indexOf

indexOf 메서드는 대상 문자열에서 인수로 전달받은 문자열을 검색하여 첫 번째 인덱스를 반환한다. 검색에 실패하면 -1을 반환한다.

const str = 'Hello World';
str.indexOf('H'); // 0
str.indexOf('or'); // 7
str.indexOf('x'); // -1

str.indexOf('l', 3); // 3 , 인덱스 3부터 l을 검색하여 첫 번째 인덱스 반환

String.prototype.search

search 메서드는 대상 문자열에서 인수로 전달받은 정규 표현식과 매치하는 문자열을 검색하여 일치하는 문자열의 인덱스를 반환한다. 검색에 실패하면 -1을 반환한다.

const str = 'Hello World';

str.search(/o/); // 4

String.prototype.includes

ES6에서 도입된 includes 메서드는 대상 문자열에 인수로 전달받은 문자열이 포함되어 있는지 확인하여 boolean으로 반환한다.

const str = 'Hello World';

str.includes('Hello'); // true
str.includes('l', 3); // true

String.prototype.startsWith

ES6에서 도입된 startsWith 메서드는 대상 문자열이 인수로 전달받은 문자열로 시작하는지 확인하여 boolean으로 반환한다.

const str = 'Hello World';

str.startsWith('He'); // true

String.prototype.endsWith

ES6에서 도입된 endsWith 메서드는 대상 문자열이 인수로 전달받은 문자열로 끝나는지 확인하여 그 결과를 true 또는 false로 반환한다.

const str = 'Hello World';

str.endsWith('ld'); // true

String.prototype.charAt

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

const str = 'Hello World';

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

❗ 인덱스가 문자열의 범위를 벗어난 정수인 경우 빈 문자열을 반환

String.prototype.substring

substring 메서드는 대상 문자열에서 첫 번째 인수로 전달받은 인덱스에 위치하는 문자부터 두 번째 인수로 전달받은 인덱스에 위치하는 문자의 바로 이전 문자까지의 부분 문자열을 반환한다.

const str = 'Hello World';
// index 1 ~ (4-1) 까지 부분 문자열 반환
str.substring(1, 4); // ell
str.substring(1); // ello World

String.prototype.slice

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

const str = 'Hello World';

str.substring(0, 5); // hello
str.slice(0, 5); // hello
str.slice(-5); // world

String.prototype.toUpperCase(.toLowerCase)

toUpperCase(toLowerCase) 메서드는 대상 문자열을 모두 대문자(소문자)로 변경한 문자열을 반환한다.

const str = 'Hello World';

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

String.prototype.trim

trim 메서드는 대상 문자열 앞뒤에공백 문자가 있을 경우 이를 제거한 문자열을 반환한다.

const str = '  foo  ';
str.trim(); // 'foo'

String.prototype.repeat

ES6에서 도입된 repeat 메서드는 대상 문자열을 인수로 전달받은 정수만큼 반복해 연결한 새로운 문자열을 반환한다.

const str = 'abc';
str.repeat(0); // ''
str.repeat(1); // 'abc'
str.repeat(3); // 'abcabcabc'
str.repeat(01); // ❌ RangeError: Invalid count value

String.prototype.replace

replace 메서드는 대상 문자열에서 첫 번째 인수로 전달받은 문자열 또는 정규표현식을 검색하여 두 번째 인수로 전달한 문자열로 치환한 문자열을 반환한다.

const str = 'Hello world';

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

String.prototype.split

split 메서드는 대상 문자열에서 첫 번째 인수로 전달한 문자열 또는 정규 표현식을 검색하여 문자열을 구분한 후 분리된 각 문자열로 이루어진 배열을 반환한다.

const str = 'How are you doing?';

str.split(' '); // [ 'How', 'are', 'you', 'doing?' ]
profile
Frontend 개발자입니다 😎

0개의 댓글