본문 바로가기

■ 프로그래밍/JavaScript

문자열 메소드 - slice, charAt, split, replace, indexOf

몇 가지 자주 사용되는 배열 문자 관련 프로퍼티와 메소드를 알아두면 코드를 짤 때 훨씬 편하다. 

 

1. 문자열.slice(start, end)

slice는 문자를 추출할 때 사용된다. 

var yes = "Today is the day.";

console.log(yes.slice(0, 5)); // output: Today

위 처럼 end가 5면, 0부터 4까지 자른다. 보여지고 싶은 곳에 +1을 하고 작성해야 한다. 

 

2. 문자열.charAt()

charAt도 문자를 추출할 때 사용되지만, 하나의 인덱스만 받는다. 

var yes = "Today is the day.";

console.log(yes.charAt(0)); // output: T

 

3. 문자열.split()

split는 문자열을 분할 할 때 사용된다. () 안에 어떤 것을 기준으로 분할 할 것인지 입력하면 된다. 

var yes = "Today is the day.";

console.log(yes.split(' ')); // output: ["Today", "is", "the", "day."]

 

4. 문자열.replace(current, new)

replace는 문자를 대체한다. 

var yes = "Today is the day.";

console.log(yes.replace("Today", "Tomorrow")); // output: Tomorrow is the day.

 

5. 문자열.indexOf()

indexOf는 해당 문자열에서 찾고자 하는 단어의 인덱스를 알려준다. 

var yes = "Today is the day.";

console.log(yes.indexOf("the")); // output: 9

만약 해당 문자열에 찾고자 하는 것이 없다면 -1이 출력된다. 

var yes = "Today is the day.";

console.log(yes.indexOf("Yesterday")); // output: -1

 

이번 글에서 소개한 문자열 프로퍼티는 배열에서도 사용이 가능하다.