본문 바로가기

Web[웹]/자바스크립트

문자열(String) 주요 메서드 파악하기

1. 문자열 접근

 

str[index]
1
2
3
4
5
6
7
8
9
let str = "Cook";
 
console.log(str[0]); // "C"
console.log(str[100]); // undefined
console.log(str[str.length - 1]); // "k"
 
/* Read-only로 해당 인덱스 값 쓰기 불가 */
str[0= "B";
console.log(str); // "Cook"
cs

 

2. 문자열 합치기 ( + )

 

str + str

- '+' 연산자를 통해 문자열 합치기가 가능합니다.

- 'string'타입과 다른 타입 사이에 '+'연산자를 사용하면, 합쳐진 타입은 'string'입니다.

 

1
2
3
4
5
6
7
8
9
10
let str1 = "Apple";
let str2 = "Pie";
console.log(str1 + str2); // "ApplePie"
 
/* string 과 다른 타입 더하기 */
let str3 = "test"
let arr = ["a""b""c"];
let num = 100;
console.log(str3+arr); // "testa,b,c"
console.log(str3+num); // "test100"
cs

 

 

3. 문자열 찾기 (indexOf, includes)

 

indexOf()

 

str.indexOf(searchString, position)

- searchString: 찾고자 하는 문자열을 적습니다.

- position: searchString를 찾기 시작하는 위치를 나타내는 인덱스 값입니다.

- 반환값: searchString 중, 첫 번째로 나온 인덱스를 리턴합니다. 만약 찾을 수 없으면 '-1'을 리턴합니다.

 

1
2
3
4
let pet = "Meow Meow Cats";
pet.indexOf("Meow"); //  0 (첫번째로 찾은 값 출력)
pet.indexOf("meow"); // -1 (없을 경우 -1 출력)
pet.indexOf("Cats"); // 10
cs

 


includes()

 

str.includes(searchString, position)

 

- searchString: 찾고자 하는 문자열을 적습니다.

- position: searchString를 찾기 시작하는 위치를 나타내는 인덱스 값입니다.

- 반환값: 문자열을 찾았을 경우 true, 찾지 못했을 경우 false를 리턴합니다.

 

※ Internet Explorer에서는 지원을 하지 않습니다.

 

1
2
pet.includes("Meow"); // true
pet.includes("meow"); // false
cs

 

 

4. 문자열 분리하기 (split)

 

split()

 

str.split(separator, limit)

 

separator: 분리 기준이될 문자열을 적습니다.

- limit: 분리된 문자열의 최대 개수를 나타내는 정수입니다. 배열의 원소가 limit개가 되면 멈춥니다.

반환값: 분리된 문자열이 포함된 배열을 리턴합니다.

 

※ separator 구분자로 빈 문자열("")을 넣으면, UTF-16 코드 유닛으로 나누게 되며 써로게이트 페어가 망가질 수 있습니다.

 

1
2
3
4
5
let fruit = "red,blue,green,orange";
let text = "My name is Bob";
console.log(fruit.split(',')); // [ 'red', 'blue', 'green', 'orange' ]
console.log(text.split(" ")); // [ 'My', 'name', 'is', 'Bob' ]
console.log(text.split(" "2)); // [ 'My', 'name' ]
cs

 

 

5. 문자열 자르기 (substring, slice)

※substring과 slice는 거의 유사하나 몇가지 차이점을 보입니다.

substring()

 

str.substring(indexStart, indexEnd)

 

- indexStart: 시작 인덱스

- indexEnd: 끝 인덱스 (해당 인덱스는 포함안함) [생략 시 마지막까지]

- 반환값: 시작과 끝을 기준으로 나눈 부분 문자열을 리턴합니다.

 

차이점

- indexStart가 indexEnd보다 크면 서로 자리를 바꿉니다. (indexStart ↔ indexEnd)

- indexStart나 indexEnd가 음수이거나 NaN이면 0을 사용합니다.

 

1
2
3
4
5
6
let num = ("0123456789");
console.log(num.substring(35)); // "34" (5번째 index 포함X)
console.log(num.substring(520));// "56789" (End범위 초과 시)
/* slice()와 다른 점 */
console.log(num.substring(-33));// "012" (음수일 때 0을 사용)
console.log(num.substring(30)); // "012" (Start가 End보다 클 경우)
cs

 


 

slice()

 

str.slice(indexStart, indexEnd)

 

- indexStart: 시작 인덱스

- indexEnd: 끝 인덱스 (해당 인덱스는 포함안함)

- 반환값: 시작과 끝을 기준으로 나눈 부분 문자열을 리턴합니다.

 

차이점

- indexStart가 indexEnd보다 크면 빈 문자열(Empty string)을 반환합니다.

- indexStart나 indexEnd가 음수이면, 문자열의 가장 뒤에서 음수만큼 내려온 index로 취급합니다.

 

1
2
3
4
5
6
7
let num = ("0123456789");
console.log(num.slice(35));     // "34" (5번째 index 포함X)
console.log(num.slice(5));        // "56789" (End인자가 없을때 문자열 끝까지)
console.log(num.slice(520));    // "56789" (End범위 초과 시)
/* substring()과 다른 점 */
console.log(num.slice(-3-1));   // "78" (음수일 때 뒤를 기준)
console.log(num.slice(30));     // "" (Start가 End보다 클 경우)
cs

 

 

6. 문자열 대·소문자 변환 (toUpperCase, toLowerCase)

 

toUppercase / toLowerCase()

 

str.toUpperCase()
str.toLowerCase()

 

- toUpperCase는 대문자로 변환, toLowerCase는 소문자로 변환해주며, 따로 인자는 없습니다.

- 반환값: 리턴되는 값은 대·소문자로 변환된 배열이다.

 

 

1
2
3
4
5
let text = "AAbbCCdd";
let upper = text.toUpperCase();
let lower = text.toLowerCase();
console.log(upper); // "AABBCCDD"
console.log(lower); // "aabbccdd"
cs

 

 

7. 문자열 공백제거하기 (trim)

 

trim()

 

str.trim()

 

- 문자열 양 끝의 공백을 제거합니다.

- 반환값: 양 끝에서 공백을 제거한 새로운 문자열을 리턴합니다.

 

1
2
let spaceText = "   H  e llo!      ";
console.log(spaceText.trim()); // "H  e llo!" (내부 공백은 제거안됨)
cs