String 프로퍼티와 String 메서드

se-een·2022년 10월 13일
0
post-thumbnail

이 글은 '이웅모'님의 '모던 자바스크립트 Deep Dive' 책을 통해 공부한 내용을 정리한 글입니다. 저작권 보호를 위해 책의 내용은 요약되었습니다.

String 생성자 함수

표준 빌트인 객체인 String 객체는 new 연산자와 함께 호출하여 String 인스턴스를 생성할 수 있다. new 연산자를 사용하지 않으면 인스턴스 대신 문자열을 반환한다. 이를 통해 명시적 타입 변환을 할 수 있다.


String 프로퍼티

length

  • 기능 : 문자열의 길이를 반환한다.
  • 반환 : 문자열의 길이
"Hi".length; // 2
"abc123ㄱㄴㄷ".length; // 9

String 메서드

배열 메서드는 원본 배열을 직접 수정하거나 새로운 배열을 반환하는 두 가지 타입의 메서드가 존재한다. String 메서드는 원본 문자열을 직접 변경하는 메서드는 없다. 문자열은 변경 불가능한 원시값이기 때문이다. 아래에선 자주 사용할 법한 메서드만 정리하였다.

String.prototype.indexOf

  • 기능 : 인수로 전달받은 문자열을 검색하여 첫 번째 인덱스를 반환한다.
  • 반환 : 인덱스 값 또는 -1
const str = "hello";

str.indexOf("e"); // 1
str.indexOf("김"); // -1

String.prototype.search

  • 기능 : 인수로 전달받은 정규표현식으로 검색하여 일치하는 문자열의 인덱스를 반환한다.
  • 반환 : 인덱스 값 또는 -1
const str = "hello";

str.search(/e/); // 1
str.search(/k/); // -1

String.prototype.includes

  • 기능 : 인수로 전달받은 문자열이 포함되어 있는지 알려준다.
  • 반환 : true 또는 false
const str = "hello";

str.includes("he"); // true
str.includes("김"); // false

String.prototype.charAt

  • 기능 : 인수로 전달받은 인덱스에 위치한 문자를 반환한다.
  • 반환 : 문자 또는 ''
const str = "hello";

str.charAt(1); // 'e'
str.charAt(5); // ''

String.prototype.slice

  • 기능 : 인수로 전달받은 범위만큼 문자열을 반환한다. substring보다 더 확장된 기능
  • 반환 : 문자열
const str = "hello";

// 첫 번째 인수 : 시작 위치(포함)
// 두 번째 인수 : 끝낼 위치(미포함)
str.slice(0, 3); // 'hel'
str.substring(0, 3); // 'hel'

str.slice(1); // 'ello'
str.substring(1); // 'ello'

str.slice(-2); // 'lo'
str.substring(-2); // 'hello' // 인수가 <0, NaN일 경우 0으로 취급

String.prototype.toUpperCase

  • 기능 : 대상 문자열을 모두 대문자로 변경한다.
  • 반환 : 대문자로 변경된 문자열
const str = "hello";

str.toUpperCase(); // 'HELLO'

String.prototyep.toLowerCase

  • 기능 : 대상 문자열을 모두 소문자로 변경한다.
  • 반환 : 소문자로 변경된 문자열
const str = "HELLO";

str.upLowerCase(); // 'hello'

String.prototype.trim

  • 기능 : 문자열 앞뒤에 공백이 있을 경우 제거한다.
  • 반환 : 공백이 제거된 문자열
const str1 = "  hello ";
const str2 = "h e l l o"

str1.trim(); // 'hello'
str2.trim(); // 'h e l l o'

String.prototype.split

  • 기능 : 인수로 전달된 값으로 문자열을 구분한 배열을 반환한다.
  • 반환 : 배열
const str = "hello world";

str.split(""); // (11) ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
str.split(" "); // (2) ['hello', 'world']

String.prototype.repeat

  • 기능 : 인수로 전달받은 값만큼 대상 문자열을 반복해 새로운 문자열로 반환한다.
  • 반환 : 문자열 또는 빈문자열, RangeError
const str = 'hello';

str.repeat(0); // ''
str.repeat(2); // 'hellohello'
str.repeat(-1); // RangeError

String.prototype.replace

  • 기능 : 첫 번째 인수로 전달받은 문자열 또는 정규표현식을 검색하여 두 번째 인수로 전달받은 문자열로 치환한 문자열을 반환한다.
  • 반환 : 변경한 문자열
  • 인수
    • 첫 번째 : 변경하고자 하는 문자열 또는 정규표현식
    • 두 번째 : 변경할 문자열 값
const str = 'hello world';

str.replace('world', 'Kim'); // 'hello Kim'
str.replace(/l/gi, 'L'); // 'heLLo worLd'

// 특수 교체 패턴 $&
str.replace('world', '<div>$&</div>'); // 'hello <div>world</div>'
profile
woowacourse 5th FE

0개의 댓글