본문 바로가기

JS

[JS] String(표준 빌트인 객체)의 프로퍼티와 메서드


length 프로퍼티

  • 문자열의 문자 개수를 반환하는 프로퍼티

String 메서드

String 객체의 메서드는 원본 String 래퍼 객체를 직접 변경하지 않고, 새로운 문자열을 반환한다.

※ 사용 빈도가 높은 메서드 위주로 정리

String.prototype.indexOf(searchValue, *fromIndex)

  • 대상 문자열에서 searchValue를 검색하여 위치를 알려주는 메서드
  • searchValue가 여러개 존재할 경우에 첫번째 위치한 인덱스를 반환한다.
  • 대상 문자열에 searchValue가 없으면 -1을 반환한다.
  • searchValue의 길이는 상관없다.
  • fromIndex는 검색을 시작할 인덱스를 전달한다.(옵션)
  • 특정 문자열이 존재하는지 확인하는 용도로 많이 사용된다.(includes 메서드가 더 가독성이 좋다.)
const str = 'Hello JavaScript';

str.indexOf('S');       // → 10
str.indexOf('l');       // → 2
str.indexOf(' ');       // → 5
str.indexOf('Java');    // → 6
str.indexOf('d');       // → -1

// str의 인덱스 8('v')부터 검색 시작
str.indexOf('a', 8);    // → 9

// 특정 문자열 존재 확인(indexOf, includes 메서드 활용)
if (str.indexOf('Java') !== -1) {
  console.log('존재합니다.');
}

if (str.includes('Java')) {
  console.log('존재합니다.');
}

 

String.prototype.search(regexp)

  • 대상 문자열에서 regexp을 검색하여 위치를 알려주는 메서드
  • regexp은 정규 표현식을 사용해야 한다.
  • 검색에 실패하게 되면 -1을 반환한다.

 

String.prototype.includes(searchString, *position)

  • 대상 문자열에서 searchString이 포함되어 있는지 확인하는 메서드
  • 포함하고 있으면 true, 없으면 false를 반환한다.
  • position은 검색을 시작할 인덱스를 전달한다.(옵션)
const str = 'Hello JavaScript';

str.includes('Java');   // → true
str.includes('');       // → true
str.includes('d');      // → false
str.includes();         // → false

// str의 인덱스 8('v')부터 검색 시작
str.indexOf('a', 8);    // → true
str.indexOf('o', 8);    // → false

 

String.prototype.startsWith(searchString, *position)

  • 대상 문자열이 searchString으로 시작하는지 확인하는 메서드
  • 시작하면 true, 없으면 false를 반환한다.
  • position은 검색을 시작할 인덱스를 전달한다.(옵션)
const str = 'Hello JavaScript';

str.startsWith('He');      // → true
str.startsWith('d');       // → false

// str의 인덱스 6('J')부터 검색
str.startsWith('Java', 6); // → true

 

String.prototype.endsWith(searchString, *length)

  • 대상 문자열이 searchString으로 끝는지 확인하는 메서드
  • 끝나면 true, 없으면 false를 반환한다.
  • length는 검색할 문자열의 길이를 전달한다.(옵션, 대상 문자열의 처음부터 length자리까지 제한)
const str = 'Hello JavaScript';

str.endsWith('ipt');   // → true
str.endsWith('p');     // → false

// str의 처음부터 5(' ')자리까지 확인(str의 인덱스 5가 아님)
str.endsWith('lo', 5); // → true

 

String.prototype.charAt(index)

  • 대상 문자열에서 해당 위치(index)의 문자를 알려주는 메서드
  • index에 해당하는 문자를 반환한다.
  • index의 범위는 0에서 (문자열 길이 - 1) 사이의 정수다.
  • index 생략 시, 기본값으로 0이 설정되고, 첫 번째 문자를 반환한다.
  • 범위를 벗어나면 빈 문자열을 반환한다.
const str = 'Hello JavaScript';

str.charAt();    // → "H"
str.charAt(16);  // → ""

// console 창에 'Hello JavaScript' 출력
for (let i = 0; i < str.length; i++) {
  console.log(str.charAt(i)); 
}

 

String.prototype.substring(indexStart, *indexEnd)

  • 대상 문자열 내에서 지정된 범위만큼 출력하는 메서드
  • indexStart부터 (indexEnd - 1)까지 부분 문자열을 반환한다.
  • indexEnd를 생략시, indexStart부터 마지막 문자까지 부분 문자열을 반환한다.(옵션)
  • 기본적으로 indexStart < indexEnd가 정상이지만, 다음 이하의 경우에도 정상 작동한다.
    • (indexStart > indexEnd)인 경우 → 두 인수(indexStart, indexEnd) 값이 교환된다.
    • indexStart, indexEnd 값이 0보다 작거나 NaN인 경우 → 인수가 0으로 취급된다.
    • (indexStart || indexEnd) > (대상 문자열의 길이)인 경우 → 인수가 대상 문자열의 길이 값으로 취급된다.
  • indexOf 메서드와 함께 응용하면 유용하다.
const str = 'Hello JavaScript';

str.substring(1, 5);     // → 'ello'
str.substring(6);        // → 'JavaScript'
str.substring(5, 1);     // → 'ello'
str.substring(-4);       // → 'Hello JavaScript'
str.substring(-4, -2);   // → ''
str.substring(21);       // → ''
str.substring(6, 100);   // → 'JavaScript'

// indexOf 메서드 응용(공백 문자 기준으로 문자열 취득)
str.substring(str.substring(str.indexOf(' ') + 1, str.length);); // → 'JavaScript'

 

String.prototype.slice(beginIndex, endIndex)

  • substring 메서드와 동일하게 작동한다.
  • 음수인 인수를 전달받을 수 있다.(-n을 받게 되면, 뒤에서 n자리까지 잘라내어 부분 문자열을 반환한다.)
const str = 'Hello JavaScript';

str.slice(6, 16);    // → 'JavaScript'
str.slice(6);        // → 'JavaScript'
str.slice(-6);       // → 'Script'

 

String.prototype.toUpperCase()

  • 대상 문자열을 모두 대문자로 변경하는 메서드

 

String.prototype.toLowerCase()

  • 대상 문자열을 모두 소문자로 변경하는 메서드
const str = 'aBcDeFgHiJ';

str.toUpperCase(); // → ABCDEFGHIJ
str.toLowerCase(); // → abcdefghij

 

String.prototype.trim()

  • 대상 문자열 앞뒤에 공백 문자를 제거하는 메서드
  • trimStart, trimEnd 메서드 사용 시, 대상 문자열의 제일 앞 또는 뒤의 공백 문자를 제거한다.
const str = '  apple    ';

str.trim();        // → 'apple'
str.trimStart();   // → 'apple    '
str.trimEnd();     // → '  apple'

 

String.prototype.repeat(count)

  • 대상 문자열을 지정된 횟수만큼 반복하여 반환하는 메서드
  • count 값에 따라 상황이 달라진다.
    • count === 0 → 빈 문자열 반환
    • count 생략 → 기본값 0이 설정
    • count < 0 → RangeError 발생
    • count 양의 소수 → count 내림처리
const str = 'abcde';

str.repeat(2);       // → 'abcdeabcde'
str.repeat(0);       // → ''
str.repeat();        // → ''
str.repeat(-1);      // → RangeError: Invalid count value
str.repeat(-99);     // → RangeError: Invalid count value
str.repeat(2.459);   // → 'abcdeabcde'
str.repeat(2.795);   // → 'abcdeabcde'

 

String.prototype.replace(regexp || substr, newSubstr || replacerFunction)

  • 대상 문자열 내에 특정 문자열을 검색하여 지정한 문자열로 치환시켜주는 메서드
  • 첫 번째 인수는 문자열이나 정규표현식을 사용하고, 두 번째 인수는 문자열이나 치환 함수 사용 가능하다.
  • 검색된 문자열이 여러 개일 경우, 첫 번째로 검색된 문자열만 치환한다.
  • 특수한 교체 패턴을 사용할 수 있다.
const str = 'Hello JavaScript JavaScript';

str.replace('JavaScript', 'Python');  // → 'Hello Python JavaScript'

 

String.prototype.split(*separator, *limit)

  • 지정 문자열 기준으로 대상 문자열을 분리하여 배열로 반환하는 메서드
  • separator가 빈 문자열이면 대상 문자열 내 모든 문자들이 분리된다.
  • limit는 반환될 배열의 길이를 제한한다.
  • 인수가 생략되면 대상 문자열이 그대로 요소가 되는 배열이 된다.
const str = 'How are you doing?';

str.split(' ');     // → ["How", "are", "you", "doing?"]
str.split('');      // → ["H", "o", "w", " ", "a", "r", "e", " ", "y", "o", "u", " ", "d", "o", "i", "n", "g", "?"]
str.split(' ', 3);  // → ["How", "are", "you"]
str.split();        // → ["How are you doing?"]

 


참고

 

모던 자바스크립트 Deep Dive: 자바스크립트의 기본 개념과 동작 원리

269개의 그림과 원리를 파헤치는 설명으로 ‘자바스크립트의 기본 개념과 동작 원리’를 이해하자! 웹페이지의 단순한 보조 기능을 처리하기 위한 제한적인 용도로 태어난 자바스크립트는 과도

wikibook.co.kr

 

 

String - JavaScript | MDN

String 전역 객체는 문자열(문자의 나열)의 생성자입니다.

developer.mozilla.org

'JS' 카테고리의 다른 글

[JS] Math(표준 빌트인 객체)의 프로퍼티와 메서드  (0) 2021.09.06
[JS] Number(표준 빌트인 객체)의 프로퍼티와 메서드  (0) 2021.09.03
[JS] 객체 리터럴  (0) 2021.06.20
[JS] 함수  (0) 2021.06.16
[JS] 배열 응용하기  (0) 2021.06.15