indexOf()
indexOf()는 특정 문자나 문자열이 앞에서부터 처음 발견되는 인덱스(숫자)를 반환하며 만약 찾지 못했을 경우 "-1"을 반환합니다.
"문자열.indexOf(검색값)"
"문자열.indexOf(검색값,위치값)"
//즉, 이런 방식 입니다.
const str1 = "sleep cat cute"
const currentStr1 = str1.indexOf("sleep"); //0
const currentStr2 = str1.indexOf("cat"); //5
const currentStr3 = str1.indexOf("c",0); //-1 //데이터가 없으면 -1이 나온다.
const currentStr4 = str1.indexOf("cute",10); //8
indexOf()는 여러 방식으로 정리해 보았을 때 아래 예시 처럼 나옵니다.
const str1 = "javascript reference";
const currentStr1 = str1.indexOf("javascript"); //0(번째)
const currentStr2 = str1.indexOf("reference"); //11(번째)
const currentStr3 = str1.indexOf("j"); //0(번째)
const currentStr4 = str1.indexOf("a"); //1(번째)(제일 첫번째)
const currentStr5 = str1.indexOf("v"); //2(번째)
const currentStr6 = str1.indexOf("jquery"); //-1 (데이터가 없을때)
const currentStr7 = str1.indexOf("b"); //-1 (데이터가 없을때)
const currentStr8 = str1.indexOf("javascript",0); //0
const currentStr9 = str1.indexOf("javascript",1); //-1
const currentStr10 = str1.indexOf("reference",0); //11
const currentStr11 = str1.indexOf("reference",1); //11
const currentStr12 = str1.indexOf("reference",11); //11
const currentStr13 = str1.indexOf("reference",12); //-1
lastIndexOf()
lastIndexOf()는 특정 문자나 문자열이 뒤에서부터 처음 발견되는 인덱스(숫자)를 반환하며 만약 찾지 못했을 경우 "-1"을 반환합니다.
"문자열.lastIndexOf(검색값)"
"문자열.lastIndexOf(검색값,위치값)"
//즉, 이런 방식 입니다.
const str1 = "sleep cat cute"
const currentStr1 = str1.lastIndexOf("sleep"); //0
const currentStr2 = str1.lastIndexOf("cat"); //5
const currentStr3 = str1.lastIndexOf("c"); //4 //뒤에서 부터 숫자를 셈
const currentStr4 = str1.lastIndexOf("c",0); //-1 //데이터가 없으면 -1이 나온다.
lastIndexOf()는 여러 방식으로 정리해 보았을 때 아래 예시 처럼 나옵니다.
const str1 = "javascript reference";
const currentStr14 = str1.lastIndexOf("javascript"); //0
const currentStr15 = str1.lastIndexOf("reference"); //11
const currentStr16 = str1.lastIndexOf("j"); //0(번째)
const currentStr17 = str1.lastIndexOf("a"); //3(번째)
const currentStr18 = str1.lastIndexOf("v"); //2(번째)
const currentStr19 = str1.lastIndexOf("jquery"); //-1 (데이터가 없을때)
const currentStr20 = str1.lastIndexOf("b"); //-1 (데이터가 없을때)
const currentStr21 = str1.lastIndexOf("javascript",0); //0
const currentStr22 = str1.lastIndexOf("javascript",1); //0
const currentStr23 = str1.lastIndexOf("reference",0); //-1
const currentStr24 = str1.lastIndexOf("reference",1); //-1
const currentStr25 = str1.lastIndexOf("reference",11); //11
const currentStr26 = str1.lastIndexOf("reference",12); //11
'Javascript' 카테고리의 다른 글
소문자&대문자 | 공백 (2) | 2022.08.17 |
---|---|
문자열 결합 / 템플릿 문자열 (1) | 2022.08.17 |
slice() / substring() / substr() (4) | 2022.08.16 |
정규식 표현 (4) | 2022.08.16 |
내장 함수 (4) | 2022.08.13 |
댓글