반응형
slice() / substring() / substr() 메서드(문자열 추출)
문자열에서 원하는 값을 추출하여 문자열을 반환하는 메서드입니다.
01. slice()
"문자열".slice(시작위치)
"문자열".slice(시작위치, 끝나는위치) // 시작 위치의 값은 끝나는 위치 값보다 작아야 합니다.
"문자열".slice(시작위치, 끝나는위치) // 시작 위치의 값은 끝나는 위치 값보다 작아야 합니다.
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, 2); //a
const currentStr8 = str1.slice(1, 3); //av
const currentStr9 = str1.slice(1, 4); //avs
const currentStr10 = str1.slice(-1); //e
const currentStr11 = str1.slice(-2); //ce
const currentStr12 = str1.slice(-3); //nce
const currentStr13 = str1.slice(-3, -1); //nc
const currentStr14 = str1.slice(-3, -2); //n
const currentStr15 = str1.slice(-3, -3); //''
02. substring()
substring() : 시작값이 끝나는 값보다 클 경우 두 값을 바꿔서 처리(에러 방지)
const str1 = "javascript reference";
const currentStr16 = str1.slice(1, 4); //ava
const currentStr17 = str1.slice(4, 1); //''
const currentStr18 = str1.substring(4, 1); //ava
const currentStr19 = str1.substring(1, 4); //ava
// substing은 시작위치와 끝나는위치 순서가 바뀌어도 자동으로 바꾸어 출력해줍니다.
03. substr()
"문자열".substr(시작위치)
"문자열".substr(시작위치, 길이)
"문자열".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 currentStr24 = str1.substr(0, 2); //ja
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
반응형
'Javascript' 카테고리의 다른 글
문자열 결합 / 템플릿 문자열 (4) | 2022.08.17 |
---|---|
정규표현식 (10) | 2022.08.16 |
indexOf() / lastIndexOf() (9) | 2022.08.16 |
내장 함수 (6) | 2022.08.15 |
배열 메서드 (9) | 2022.08.11 |
댓글