자바스크립트에서 문자열을 자르는 방법은 substr(), substring(), slice() 의 함수 3가지가 있다. 비슷하지만 세부적인 기능이 다르기 때문에 이를 구분하여 상황에 적절한 함수를 사용하자.
str.substr(start[, length])
str.substring(indexStart[, indexEnd])
str.slice(beginIndex[, endIndex])
//위 세 가지 함수의 인수 중 대괄호([]) 부분은 생략 가능하며, 생략할 경우 시작 위치부터 문자열 끝까지 자른다.
substr() 함수로 문자열 자르기
var str = '자바스크립트';
var result1 = str.substr(0, 2);
//결과 : "자바"
var result2 = str.substr(2, 4);
//결과 : "스크립트"
var result3 = str.substr(2);
//결과 : "스크립트"
substr("시작 위치", "길이") 또는 substr("시작 위치") 함수는 시작 위치부터 해당 길이만큼 문자열을 자르는 아주 기본적인 함수이다. "길이" 부분을 생략할 경우 시작 위치부터 문자열 끝까지 자른다.
substring() 함수로 문자열 자르기
var str = '자바스크립트';
var result1 = str.substring(0, 2);
//결과 : "자바"
var result2 = str.substring(2, 5);
//결과 : "스크립"
var result3 = str.substring(2, 6);
//결과 : "스크립트"
var result4 = str.substring(2);
//결과 : "스크립트"
substring("시작 위치", "종료 위치") 또는 substring("시작 위치") 함수는 시작 위치에서 종료 위치까지 문자열을 자른다. 주의할 점은 종료 위치의 -1까지 문자열을 자른다는 것이다.
substring() 함수에서 음수(-) 사용 시 주의사항
var str = '자바스크립트';
var result1 = str.substring(-4, 5); //str.substring(0, 5)
// 결과 : "자바스크립"
var result2 = str.substring(2, -1); //str.substring(0, 2)
// 결과 : "자바"
substring() 함수에서 인자에 음수를 대입하면 해당 값은 "0"으로 치환되며, 종료 위치에 음수 또는 "0"을 대입하면 첫 번째 인수와 두 번째 인수가 서로 뒤바뀐다.
slice() 함수로 문자열 자르기 (뒤에서부터 자르기)
var str = '자바스크립트';
var result1 = str.slice(0, 2);
//결과 : "자바"
var result2 = str.slice(2, 6);
//결과 : "스크립트"
var result3 = str.slice(2);
//결과 : "스크립트"
/************************************/
var result4 = str.slice(-4);
//결과 : "스크립트"
var result5 = str.slice(-4, 5);
//결과 : "스크립"
var result6 = str.slice(2, -1);
//결과 : "스크립"
slice("시작 위치", "종료 위치") 또는 slice("시작 위치") 함수는 기본적인 사용법은 substring() 함수와 동일하며, 다른 점은 음수를 자유롭게 사용할 수 있어서 뒤에서부터 문자열을 자를 때 유용하게 사용할 수 있다.
slice() 함수는 문자열을 뒤에서부터 자르는 str.slice(-4) 이 부분만 확실히 이해하면 될 것 같다. 문자열의 뒤에서 4 번째 자리부터 끝까지 문자열을 자르라는 의미이다.
'JavaScript' 카테고리의 다른 글
[JavaScript] 팩토리얼(Factorial) 계산 방법 3 가지 (0) | 2023.07.05 |
---|---|
[JavaScript] Array의 map, filter, reduce, forEach 메소드 (0) | 2023.06.29 |
[JavaScript] 배열 합치기 3가지 방법 (0) | 2023.06.26 |
[JavaScript] 배열 slice 메서드 (0) | 2023.06.23 |
[JavaScript] 배열 sort 메서드 (0) | 2023.06.22 |