본문 바로가기
JAVASCRIPT

메서드 (indexOf / lastIndexOf)

by 코빈_ 2022. 8. 16.

indexOf() / lastIndexOf()

문자열에서 특정 문자의 위치를 찾고 숫자를 반환하는 메서드이다.

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


    const str1 = "javascript reference"
    
    const currentStr1 = str1.indexOf("javascipt")               // 00
    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("jqeurey")                  // -1
    const currentStr8 = str1.indexOf("javascipt", 0)           // 0
    const currentStr9 = str1.indexOf("javascipt", 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 currentStr14 = str1.lastIndexOf("javascipt")                 // 0
    const currentStr15 = str1.lastIndexOf("reference")                // 11
    const currentStr16 = str1.lastIndexOf("j")                               // 0
    const currentStr17 = str1.lastIndexOf("a")                              // 3    // 뒤에서 기준을 잡기에 3
    const currentStr18 = str1.lastIndexOf("v")                              // 2
    const currentStr19 = str1.lastIndexOf("jqeurey")                    // -1
    const currentStr20 = str1.lastIndexOf("b")                              // -1
    const currentStr21 = str1.lastIndexOf("javascipt", 0)              // 0
    const currentStr22 = str1.lastIndexOf("javascipt", 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
정규식 표현  (4) 2022.08.16
메서드 (slice / substring / substr)  (2) 2022.08.16
내장 함수  (5) 2022.08.16
메서드 (join, push, pop)  (9) 2022.08.11

댓글


INFORMATION

javascript

css

html