Giant Danio Fish
본문 바로가기
Javascript

문자열 관련 메서드 (indexOf() / lastindexOf())

by 코딩왕자 2022. 8. 16.

indexOf() / lastindexOf()

indexOf는 문자열에서 특정 문자의 위치를 찾고 숫자를 반환합니다. 일치하는 값이 없을 시 -1을 반환합니다. lastindexOf는 indexOf와 같이 위치를 찾고 숫자를 반환하지만 기준점이 끝이 시작입니다.

"문자열".indexOf(검색값)
"문자열".indexOf(검색값, 위치값)
"문자열".lastindexOf(검색값)
"문자열".lastindexOf(검색값, 위치값)

// 예시입니다.
const str1 = "javascript reference";
const currentStr1 = str1.indexOf("javascript");        //0
const currentStr2 = str2.indexOf("reference");         //11
const currentStr3 = str2.indexOf("j");                 //0
const currentStr4 = str2.indexOf("a");                 //1
const currentStr5 = str2.indexOf("v");                 //2
const currentStr6 = str2.indexOf("jquery");            //-1
const currentStr7 = str2.indexOf("b");                 //-1
const currentStr8 = str2.indexOf("javascript", 0);     //0
const currentStr9 = str2.indexOf("javascript", 1);     //-1
const currentStr10 = str2.indexOf("reference", 0);     //11
const currentStr11 = str2.indexOf("reference", 1);     //11
const currentStr12 = str2.indexOf("reference", 11);    //11
const currentStr13 = str2.indexOf("reference", 12);    //-1

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

댓글


광고 준비중입니다