Javascript의 substring VS slice

한슬희·2021년 10월 5일
2

Javascript

목록 보기
2/3

substring vs slice 뭐가 다를까? 🤔

substringslice 메소드는 문자열을 잘라주는 역할을 한다.

str.substring(indexStart[, indexEnd])
str.slice(beginIndex[, endIndex])

두 메소드는 사용법도 같아 차이점이 뭔지 더 궁금해진다.

차이점

파라미터가 음수일 경우 두 함수는 다른 결과값을 반환한다.

아래의 코드를 보면 같은 start, end인데 결과 값이 다른 모습을 볼 수 있다.

const str = "123456"

const slice = str.slice(-3, 6);
const substring = str.substring(-3, 6);

// 결과
console.log(slice); // 456
console.log(substring); // 123456
const str = "123456"

const slice = str.slice(0, -3);
const substring = str.substring(0, -3);

// 결과
console.log(slice); // 123
console.log(substring); // 안찍힘

❗ start 혹은 end가 음수일 경우

substring

substring는 start값, end값이 0으로 취급된다.

str.substring(-3, 6)의 start 값이 음수이기 때문에 0으로 취급되어 str.substring(0, 6)으로 계산된다.
str.substring(0, -3)는 end 값이 음수이기 때문에 str.substring(0, 0)으로 계산되어 아무것도 반환하지 않았다.

slice

slice는 음수 값을 입력한 경우 뒤에서부터 이동하게 된다.

str.slice(-3, 6)를 보면 start 값이 음수이기 때문에 start가 뒤에서 3번째 자리인 4인 것이다. 즉 str.slice(3, 6)로 계산된다.
end가 음수일 경우도 마찬가지로 뒤에서 음수의 절댓값만큼 내려온다. str.slice(0, -3)를 보면 뒤에서 3번째는 4이기 때문에 str.slice(0, 4)로 계산된다.

마무리


두 메소드의 퍼포먼스는 다음과 같다. 미세하지만 slice가 우위에 있는 모습을 볼 수 있다.

performance-test로 가면 초당 연산횟수을 보여준다.

👊🏻👊🏻

profile
🧡 Frontend developer / 어제보다 오늘 더 성장한 개발자

2개의 댓글

comment-user-thumbnail
2021년 10월 5일

예제를 통해 더욱 쉽게 이해할 수 있었어요 :D 좋은 정보 공유 감사합니다 ~~~ 🏄‍♀️🏄‍♀️🏄‍♀️🏄‍♀️

1개의 답글