๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ

indexOf()/lastIndexOf()

by Youcodein 2022. 8. 17.
728x90
๋ฐ˜์‘ํ˜•

indexOf()

indexOf() ๋ฉ”์„œ๋“œ๋Š” ๋ฐฐ์—ด์—์„œ ์ง€์ •๋œ ์š”์†Œ๋ฅผ ์ฐพ์„ ์ˆ˜ ์žˆ๋Š” ์ฒซ ๋ฒˆ์งธ ์ธ๋ฑ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด -1์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. indexOf()๋Š” ์ฒ˜์Œ ๋ฐœ๊ฒฌ๋˜๋Š” ๋ฌธ์ž์—ด์— ๋Œ€ํ•œ index๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ , lastIndexOf๋Š” ๋งˆ์ง€๋ง‰ ๋ฌธ์ž์—ด์˜ index๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

"๋ฌธ์ž์—ด".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 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
728x90
๋ฐ˜์‘ํ˜•

'์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

์ •๊ทœํ‘œํ˜„์‹  (4) 2022.08.17
slice() / substring() / substr()  (6) 2022.08.17
๋‚ด์žฅํ•จ์ˆ˜  (3) 2022.08.15
๋ฐฐ์—ด ๊ด€๋ จ ๋ฉ”์„œ๋“œ  (10) 2022.08.11
์š”์†Œ ์„ ํƒ์ž  (5) 2022.08.07

๋Œ“๊ธ€