프로그래머스에서 자바스크립트 코딩테스트 문제를 풀고 다른 사람의 풀이를 보는데 어떤 풀이 밑에 이런 댓글이 달려있었다.(!!) 평소에 substr과 substring, slice를 구분하지 않고 썼었는데 무슨 차이가 있는건지, substr을 권장하지 않는 이유에 대해서도 더 알아보려 한다.
1. substr()
str.substr(start, length)
substr 함수는 특정 위치에서 시작해서 특정 문자 수 만큼의 문자들을 반환한다. 파라미터로 입력받은 start 인덱스부터 length 길이만큼 string을 잘라내어 반환한다. 첫 번째 글자의 인덱스는 0부터 시작한다.
- start가 양수일 때
- 문자열 전체 길이보다 크거나 같을 경우: 빈 문자열 반환
- start가 음수일 때
- 문자열 끝에서 start 숫자만큼 뺀 곳에서 시작
- 절대값이 문자열 전체보다 클 경우: 문자열의 0 인덱스부터 시작
- length가 0 혹은 음수일 때: 빈 문자열 반환
- length가 생략: start부터 문자열의 끝까지 추출하여 반환
const str = 'Mozilla';
console.log(str.substr(1, 2));
// expected output: "oz"
console.log(str.substr(2)); //length 생략: index 2부터 끝까지
// expected output: "zilla"
substr을 권장하지 않는 이유
https://stackoverflow.com/questions/52640271/why-string-prototype-substr-seems-to-be-deprecated
Why String.prototype.substr() seems to be deprecated?
It is mentionned on the ECMAScript standard here that : ... These features are not considered part of the core ECMAScript language. Programmers should not use or assume the existence of these
stackoverflow.com
ECMAScript Standard에 아래와 같이 나와있다.
... These features are not considered part of the core ECMAScript language. Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code. ECMAScript implementations are discouraged from implementing these features unless the implementation is part of a web browser or is required to run the same legacy ECMAScript code that web browsers encounter.
substr을 권장하지 않는 이유는 이가 표준화된 언어의 일부가 아니었기 때문이라고 한다. ECMAScript 1, 2 에는 없었고 ECMAScript 3의 섹션 B.2("Additional Properties")에만 등장한다.
Some implementations of ECMAScript have included additional properties for some of the standard native objects. This non-normative annex suggests uniform semantics for such properties without making the properties or their semantics part of this standard.
웬만하면 substr보다 substring이나 slice를 쓰는 게 나을 것 같다..
2. substring()
str.substring(start, end)
substring 함수는 string 객체의 start 인덱스로부터 end 인덱스 전까지 문자열의 부분 문자열을 반환한다.
substr과 차이점은 substring은 매개변수로 잘라내고 싶은 문자열의 start 인덱스와 end 인덱스를 전달한다는 것이다. (마찬가지로 문자열의 인덱스는 0부터 시작)
- end 가 생략된 경우: 문자열의 끝까지 모든 문자 추출
- start 인덱스 = end 인덱스 인 경우: 빈 문자열 반환
- start 인덱스 > end 인덱스 인 경우: 마치 두 개의 인자를 바꾼 듯 작동 (아래 코드 예시)
0보다 작은 인자값을 가지거나 NaN 값은 0으로 처리되고 str.length보다 큰 인자 값을 가질 경우 str.length로 처리된다.
const str = 'Mozilla';
console.log(str.substring(1, 3));
// expected output: "oz"
console.log(str.substring(2));
console.log(str.substring(2,7));
// expected output: "zilla"
console.log(anyString.substring(0, 1));
console.log(anyString.substring(1, 0));
// Displays 'M'
console.log(anyString.substring(0, 7));
console.log(anyString.substring(0, 10));
// Displays 'Mozilla'
3. slice()
str.slice(start, end)
slice()는 substring과 사용법이 같다. 마찬가지로 파라미터를 자를 문자열의 start 인덱스와 end 인덱스를 전달한다.
- start 인덱스가 음수일 경우: 문자열 길이 + start 인덱스로 취급 (start가 -3이면 시작점은 str.length-3)
- start >= str.length일 경우: 빈 문자열 반환
end 인덱스는 추출 종료점 인덱스로 이 위치의 문자는 추출할 때 포함되지 않는다. (end 전까지만 추출)
- end 인덱스가 생략되었을 경우: 문자열 마지막까지 추출
- end 인덱스가 음수일 경우: 문자열 길이 + end 인덱스로 취급. (end가 -3이면 종료점은 str.length-3)
start 또는 end 값이 음수이고, 음수의 절대값이 전체 string 길이보다 큰 경우
- 이 경우에는 음수가 단순히 0으로 처리된다. (아래 코드 참조!)
let str = "안녕하세요?"
let slice_1 = str.slice(-10, 6); //str.slice(0, 6)과 동일
let slice_2 = str.slice(0, -10); //str.slice(0, 0)과 동일
console.log("slice(-10, 6) : ", slice_1); // "안녕하세요?"
console.log("slice(0, -10) : ", slice_2); // ""
substring() vs slice()
두 함수의 차이에 대해서 다시 정리해보자.
start > end 일 경우
substring은 start와 end 값을 바꿔서 처리하는 반면, slice()는 비어있는 string, ""을 리턴한다.
let str = "안녕하세요?"
let slice = str.slice(1, 0);
let substring = str.substring(1, 0);
console.log("slice(1,0) : ", slice); // ""
console.log("substring(1,0) : ", substring); // "안"
start 또는 end 값이 음수인 경우
substring()
- start값이 음수인 경우, start 값은 0으로 취급.
- end값도 마찬가지로 0으로 취급.
slice()
- string의 가장 뒤에서 음수의 절대값만큼 내려온 index로 취급. slice(-2, 6)의 경우 string의 뒤에서 2번째 자리를 start값으로 취급해 계산해 slice(4, 6)의 결과와 같게 나온다.
- end 값도 마찬가지로 slice(0, -2)의 경우 slice(0, 4)와 같게 처리된다.
let str = "안녕하세요?"
let slice_1 = str.slice(-2, 6); //str.slice(4, 6)와 동일
let slice_2 = str.slice(0, -2); //str.slice(0, 4)
let substring_1 = str.substring(-2, 6); //str.substring(0, 6)와 동일
let substring_2 = str.substring(0, -2); //str.substring(0, 0)
console.log("slice(-2, 6) : ", slice_1); // "요?"
console.log("slice(0, -2) : ", slice_2); // "안녕하세"
console.log("substring(-2, 6) : ", substring_1); // "안녕하세요?"
console.log("substring(0, -2) : ", substring_2); // ""
'FE > Javascript' 카테고리의 다른 글
[JS] Array.from을 통한 배열 초기화 (0) | 2021.08.23 |
---|---|
[JS] splice()란? - 배열 요소 추가/삭제/교체 (0) | 2021.08.13 |
[JS] map 함수 (0) | 2021.07.22 |
[JS] 배열 정렬 sort() 함수 (0) | 2021.07.14 |
자바스크립트로 난수 맞추는 게임 만들기 (0) | 2021.04.28 |