728x90
![](https://blog.kakaocdn.net/dn/Vo53H/btrJ3aDPu5z/HsnbY3UN7qgIhotpakDtEK/img.jpg)
slice() / substring() / substr()
문자열에서 원하는 값을 추출하는 메서드 입니다. 괄호 안에 시작값과 끝나는 위치 값을 넣어 원하는 단어나 글자를 출력할 수 있습니다.
01. slice()
const str1 = "sleep cat"
const currentStr1 = str1.slice(0); //sleep cat
const currentStr2 = str1.slice(5,9); //cat
시작위치보다 끝나는 위치가 더 커야지 올바르게 나옵니다.
const str1 = "javascript reference"
const currentStr1 = str1.slice(0); //javascript reference
const currentStr2 = str1.slice(1); //avascript reference
const currentStr3 = str1.slice(2); //vascript reference
const currentStr4 = str1.slice(0,1); //j
const currentStr5 = str1.slice(0,2); //ja
const currentStr6 = str1.slice(0,3); //jav
const currentStr7 = str1.slice(1,1); //(아무것도 안나옴)
const currentStr8 = str1.slice(1,2); //a
const currentStr9 = str1.slice(1,3); //av
const currentStr10 = str1.slice(1,4); //ava
const currentStr11 = str1.slice(-1); //e
const currentStr12 = str1.slice(-2); //ce
const currentStr13 = str1.slice(-3); //nce
const currentStr14 = str1.slice(-3,-1); //nc
const currentStr15 = str1.slice(-3,-2); //n
const currentStr16 = str1.slice(-3,-3); //(아무것도 안나옴)
02. substring()
substring()는 가끔씩 생기는 slice()의 오류 방지를 위해 자동적으로 시작점이 끝나는 점의 위치가 바뀌어도 올바르게 나올 수 있도록 도와줍니다.
const str1 = "sleep cat"
const currentStr1 = str1.slice(9,5); //아무것도 나오지 않는다.
const currentStr2 = str1.substring(9,5); //cat
03. substr()
substr()는 시작 위치를 지정하면 그 곳에서 부터 문자열을 출력할 수 있습니다. 똑같이 끝나는 점을 지정해줄 수 있습니다.
const str1 = "sleep cat"
const currentStr1 = str1.substr(0); //sleep cat
const currentStr2 = str1.substring(1); //leep cat
const currentStr2 = str1.substring(-1); //t
substr()는 현재 자주 쓰이지 않는 메서드 이지만 똑같이 정리해보겠습니다.
const str1 = "javascript reference"
const currentStr20 = str1.substr(0); //javascript reference
const currentStr21 = str1.substr(1); //avascript reference
const currentStr22 = str1.substr(2); //vascript reference
const currentStr23 = str1.substr(0,1); //j
const currentStr25 = str1.substr(0,3); //jav
const currentStr26 = str1.substr(1,2); //av
const currentStr27 = str1.substr(1,3); //ava
const currentStr28 = str1.substr(1,4); //avas
const currentStr29 = str1.substr(-1); //e
const currentStr30 = str1.substr(-2); //ce
const currentStr31 = str1.substr(-3); //nce
const currentStr32 = str1.substr(-1,1); //e
const currentStr33 = str1.substr(-2,2); //ce
const currentStr34 = str1.substr(-3,3); //nce
728x90
'Javascript' 카테고리의 다른 글
문자열 결합 / 템플릿 문자열 (1) | 2022.08.17 |
---|---|
indexOf() (6) | 2022.08.16 |
정규식 표현 (4) | 2022.08.16 |
내장 함수 (4) | 2022.08.13 |
join()/ push()/ pop() (8) | 2022.08.11 |
댓글