본문 바로가기
Javascript

indexOf() / lastIndexOf()

by 코딩대원 2022. 8. 17.

문자열 객체

문자열 객체에서 사용하는 메서드 중 indexOf()와 lastIndexOf에 대해 알아보는 시간을 가지도록 하겠습니다.


indexOf() / lastIndexOf

문자열에서 특정 문자의 위치를 찾고 숫자를 반환합니다.
"문자열".indexOf(검색값)
"문자열".indexOf(검색값, 위치값)
"문자열".lastIndexOf(검색값)
"문자열".lastIndexOf(검색값, 위치값)


{
    //10
    {
        // "문자열".indexOf(검색값)
        // "문자열".indexOf(검색값, 위치값)
        // "문자열".lastIndexOf(검색값)
        // "문자열".lastIndexOf(검색값, 위치값)
        
        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

        const str2 = "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 기준점 e가1 뒤가 0
        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
문자열 결합 / 템플릿 문자열  (2) 2022.08.17
문자열 객체 slice() / substring() / substr()  (5) 2022.08.17
정규식 표현  (5) 2022.08.17
내장 함수  (5) 2022.08.12

댓글


HTML
CSS

JAVASCRIPT

자세히 보기