Substring vs Substr vs Slice in JavaScript

Yunwoo Ji·2021년 6월 16일
1

JavaScript

목록 보기
4/4
post-thumbnail

Ref: https://masteringjs.io/tutorials/fundamentals/substring

String.prototype.substring()String.prototype.substr() 함수는 혼란의 흔한 원인이다. 노련한 자바스크립트 개발자들도 그들을 가끔은 섞어 사용한다. substring을 얻기 위한 세 번째 방법으로는 String.prototype.slice() 함수도 있다. 이번 시간에는 자바스크립트에서 substring을 얻는 세 가지 방법의 차이점에 대해서 알아보자.

String.prototype.substring()

substring() 함수는 자바스크립트에서 가장 흔하게 substring을 얻는 방법이다. 이 함수는 indexStart, indexEnd 두 매개 변수를 받는다. 그리고 문자열의 indexStart에서 indexEnd 이전까지의 부분을 return한다. indexEnd를 지정하지 않으면, substring() 함수는 문자열의 indexStart에서부터 끝까지의 부분을 return한다.

const str = 'Twas the night before Christmas';

let indexStart = 0;
let indexEnd = 4;
str.substring(indexStart, indexEnd); // 'Twas'

str.substring(5, 14); // 'the night'
str.substring(5); // 'the night before Christmas'

substring() 함수는 다음과 같은 특징을 가진다.

  • indexStart 혹은 indexEnd 매개 변수가 0보다 작으면, 0으로 취급된다.
  • indexEnd < indexStart 이면, 두 값을 바꿨을 때의 값과 같다.
str.substring(4, -1); // 'Twas'
str.substring(4, 0); // 'Twas'
str.substring(0, 4); // 'Twas'

String.prototype.substr()

substr() 함수 역시 흔하다. 그러나 Mozila's docs에서는 legacy한 함수로 여겨진다. 새로 코드를 작성할 때 사용하지 않는 것이 좋으나, 기존 프로젝트에서는 만날 수도 있다.

substring()과 substr()의 차이점은 두 번째 매개 변수에서 찾을 수 있다. substr()의 첫 번째 매개 변수는 start이고, 두 번째 매개 변수는 length이다.

const str = 'Twas the night before Christmas';

let start = 0;
let length = 4;
str.substr(start, length); // 'Twas'

str.substr(5, 9); // 'the night'
'the night'.length; // 9

substring()과 다르게, substr()은 음수에서 시작이 가능하다. 시작 값이 음수라면, substr() 함수가 문자열의 끝에서 반대 방향으로 카운트를 시작한다.

const str = 'Twas the night before Christmas';

let start = -9;
let length = 9;
str.substr(start, length); // 'Christmas'

'Christmas'.length; // 9

String.prototype.slice()

slice() 함수는 substring(), substr() 두 함수 보다는 덜 흔하다. 그렇지만, 이것은 substring()과 substr() 두 함수의 좋은 면들을 가지고 있다. substring() 함수와 같이, slice() 함수는 indexStart와 indexEnd를 매개 변수로 가진다. 그리고 이 함수는 legacy한 함수로 여겨지지 않는다. 그러면서도, substr() 함수와 같이 indexStart가 음수인 경우도 지원한다.

const str = 'Twas the night before Christmas';

str.slice(0, 4); // Twas
str.slice(5, 14); // the night
str.slice(-16, -10); // before
str.slice(-9); // Christmas

slice() 함수는 다음 세 가지 이유로 확실한 승자라고 할 수 있겠다.

  • legacy한 함수로 여겨지지 않는다.
  • 음수 값의 시작을 지원한다.
  • String.prototype.splice()는 없기 때문에, 이름으로 혼란을 갖지 않는다.
profile
Front-End !

0개의 댓글