[자바스크립트] 문자열

맹뿌·2021년 6월 11일
0

자바스크립트

목록 보기
4/8

"hello".toUpperCase(); 이렇게 적으면 string 객체를 생성한 것이 아니라 string 형태의 원시 자료형이 된다. 이렇게 적어도 toUpperCase와 같은 메소드를 호출할 수 있는데, 이유는 원시 자료형이여도 래퍼 객체로 임시 변환하기 때문이다. new String("hello"); 를 호출한 것처럼 임시로 변환한다는 뜻이다.

이렇게 생성된 임시 객체는 프로퍼티의 참조가 끝나면 소멸하게 된다.

var a = "hello";
a.someProperty = 111; // new String(a).someProperty = 111
a.someProperty; // undefined

1. String 객체 생성

  • string 객체 생성 방법
let strObj = new String('Lee');
console.log(strObj);   // String {0: 'L', 1: 'e', 2: 'e', length: 3, [[PrimitiveValue]]: 'Lee'}

strObj = new String(1);
console.log(strObj);   // String {0: '1', length: 1, [[PrimitiveValue]]: '1'}

2. string 객체 특징

  • 원시 타입 문자열과 string 객체는 동일하지 않음
  • string 객체는 개별 객체이기 때문에 자기 자신과만 동일
    즉, 같은 string 객체라도 동일하지 않음을 알 수 있음
var s1 = "hello";
var s2 = new String("hello");
var s3 = new String("hello");

typeof s1;   // string
typeof s2;   // object

s1 == s2;   // false
s2 == s3;   // false

3. string 메소드

charAt

인수로 전달한 index를 사용하여 index에 해당하는 위치의 문자를 반환함

const str = 'Hello';

console.log(str.charAt(0)); // H
console.log(str.charAt(1)); // e
console.log(str.charAt(2)); // l
console.log(str.charAt(3)); // l
console.log(str.charAt(4)); // o

concat

str.concat(str1, str2, ..., strN);   // 문법

var Hi = 'Hello'.concat(' World!');

2개 이상의 문자열을 연결하여 새로운 문자열을 리턴

indexOf

인수로 전달한 문자 또는 문자열을 대상 문자열에서 검색하여 처음 발견된 곳의 index를 반환
발견하지 못한 경우 -1 반환

const str = 'Hello World';

console.log(str.indexOf('o'));   // 4
console.log(str.indexOf('o', 6));   // 6번 index부터 검색 시작한다는 뜻. 7

lastIndexOf

인수로 전달한 문자 또는 문자열을 대상 문자열에서 검색하여 마지막으로 발견된 곳의 index를 반환
발견하지 못한 경우 -1 반환

const str = 'Hello World';

console.log(str.lastIndexOf('l'));   // 9
console.log(str.lastIndexOf('o', 5));   // 0번 index에서 5번 index까지만 검사한다는 뜻. 4
console.log(str.lastIndexOf('W', 5));  // W는 5번 index보다 뒤에 위치하므로 -1

replace

첫번째 인수로 전달한 문자열 또는 정규표현식을 대상 문자열에서 검색하여 두번째 인수로 전달한 문자열로 대체

const str = 'Hello world';

// 첫번째로 검색된 문자열만 대체하여 새로운 문자열을 반환
console.log(str.replace('world', 'Lee')); // Hello Lee

replace 응용 버전 확인

split

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

const str = 'How are you doing?';

// 'o'으로 구분하여 배열로 반환
console.log(str.split('o')); // [ 'H', 'w are y', 'u d', 'ing?' ]

// 공백으로 구분하여 배열로 반환. 단 요소수는 3개까지만 허용
console.log(str.split(' ', 3)); // [ 'How', 'are', 'you' ]

split 응용 버전 확인

substring

첫번째 인수로 전달한 start 인덱스에 해당하는 문자부터 두번째 인자에 전달된 end 인덱스에 해당하는 문자의 바로 이전 문자까지를 모두 반환

const str = 'Hello World'; // str.length == 11

console.log(str.substring(1, 4)); // ell

// 첫번째 인수와 두번째 인수는 교환됨
console.log(str.substring(4, 1)); // ell

substring 응용 버전 확인

slice

substring과 같은 역할

const str = 'hello world';

// 뒤에서 5자리를 잘라내어 반환한다.
console.log(str.slice(-5)); // 'world'

// 2번째부터 마지막 문자까지 잘라내어 반환
console.log(str.slice(2)); // llo world

// 0번째부터 5번째 이전 문자까지 잘라내어 반환
console.log(str.slice(0, 5)); // hello

toLowerCase

문자열의 모든 문자를 소문자로 변경

toUpperCase

문자열의 모든 문자를 대문자로 변경

trim

문자열 양쪽 끝에 있는 공백 문자를 제거한 문자열을 반환

const str = '   foo  ';

console.log(str.trim()); // 'foo'

repeat

인수로 전달한 숫자만큼 반복해 연결한 새로운 문자열을 반환
count가 0이면 빈 문자열을 반환

console.log('abc'.repeat(0));   // ''
console.log('abc'.repeat(2));   // 'abcabc'
console.log('abc'.repeat(2.5)); // 'abcabc' (2.5 → 2)

includes

인수로 전달한 문자열이 포함되어 있는지를 검사하고 결과를 boolean 값으로 반환

const str = 'hello world';
console.log(str.includes('wow'));   // false
console.log(str.includes(''));      // true

🎁 참조 및 출처

profile
무엇이든 할 수 있고, 무엇이든 될 수 있는

0개의 댓글