๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Javascript

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ : ๋ฌธ์ž์—ด ๊ฒ€์ƒ‰ ๋ฉ”์„œ๋“œ : indexOf() / lastIndexOf()

by ์ฝ”ํŒŒ์นด 2022. 8. 17.
728x90

๋ฌธ์ž์—ด ๊ฒ€์ƒ‰ ๋ฉ”์„œ๋“œ : indexOf() / lastIndexOf()

indexOf(), lastIndexOf() ๋ฉ”์„œ๋“œ๋Š” ๋ฌธ์ž์—ด์—์„œ ํŠน์ • ๋ฌธ์ž์˜ ์œ„์น˜๋ฅผ ์ฐพ๊ณ , ๊ทธ ์œ„์น˜๊ฐ’์„ ์ˆซ์ž๋กœ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.


indexOf() ๋ฉ”์„œ๋“œ

indexOf() ๋ฉ”์„œ๋“œ๋Š” ํ˜ธ์ถœํ•œ String ๊ฐ์ฒด์—์„œ ์ฃผ์–ด์ง„ ๊ฐ’๊ณผ ์ผ์น˜ํ•˜๋Š” ์ฒซ ๋ฒˆ์งธ ์ธ๋ฑ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. ์ผ์น˜ํ•˜๋Š” ๊ฐ’์ด ์—†์œผ๋ฉด -1์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.


1. indexOf() : "๋ฌธ์ž์—ด".indexOf(๊ฒ€์ƒ‰๊ฐ’)

const str1 = "javascript reference";
const currentStr1 = str1.indexOf("javascript");
const currentStr2 = str1.indexOf("reference");
const currentStr3 = str1.indexOf("j");
const currentStr4 = str1.indexOf("a"); // ๋จผ์ € ๋‚˜์˜ค๋Š” a์˜ ๊ฒ€์ƒ‰๊ฐ’๋งŒ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.
const currentStr5 = str1.indexOf("v");
const currentStr6 = str1.indexOf("jquery"); // ์ผ์น˜ํ•˜๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์„ ๋•Œ๋Š” -1์„ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.
const currentStr7 = str1.indexOf("b");
๊ฒฐ๊ณผ๋ณด๊ธฐ
0
11
0
1
2
-1
-1

2. indexOf() : "๋ฌธ์ž์—ด".indexOf(๊ฒ€์ƒ‰๊ฐ’, ์œ„์น˜๊ฐ’)

const str1 = "javascript reference";
const currentStr1 = str1.indexOf("javascript", 0);
const currentStr2 = str1.indexOf("javascript", 1);
const currentStr3 = str1.indexOf("reference", 0);
const currentStr4 = str1.indexOf("reference", 1);
const currentStr5 = str1.indexOf("reference", 11);
const currentStr6 = str1.indexOf("reference", 12);
๊ฒฐ๊ณผ๋ณด๊ธฐ
0
-1
11
11
11
-1

lastIndexOf() ๋ฉ”์„œ๋“œ

lastIndexOf() ๋ฉ”์„œ๋“œ๋Š” ์ฃผ์–ด์ง„ ๊ฐ’๊ณผ ์ผ์น˜ํ•˜๋Š” ๋ถ€๋ถ„์„ ์—ญ์ˆœ์œผ๋กœ ํƒ์ƒ‰ํ•˜์—ฌ, ์ตœ์ดˆ๋กœ ๋งˆ์ฃผ์น˜๋Š” ์ธ๋ฑ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. ์ผ์น˜ํ•˜๋Š” ๋ถ€๋ถ„์„ ์ฐพ์„ ์ˆ˜ ์—†์œผ๋ฉด -1์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.


1. lastIndexOf() : "๋ฌธ์ž์—ด".lastIndexOf(๊ฒ€์ƒ‰๊ฐ’)

const str1 = "javascript reference";
const currentStr1 = str1.lastIndexOf("javascript")
const currentStr2 = str1.lastIndexOf("reference")
const currentStr3 = str1.lastIndexOf("j")
const currentStr4 = str1.lastIndexOf("a")
const currentStr5 = str1.lastIndexOf("v")
const currentStr6 = str1.lastIndexOf("jquery")
const currentStr7 = str1.lastIndexOf("b")
๊ฒฐ๊ณผ๋ณด๊ธฐ
0
11
0
3
2
-1
-1

2. lastIndexOf() : "๋ฌธ์ž์—ด".lastIndexOf(๊ฒ€์ƒ‰๊ฐ’, ์œ„์น˜๊ฐ’)

const str1 = "javascript reference"
const currentStr1 = str1.lastIndexOf("javascript", 0)
const currentStr2 = str1.lastIndexOf("javascript", 1)
const currentStr3 = str1.lastIndexOf("reference", 0)
const currentStr4 = str1.lastIndexOf("reference", 1)
const currentStr5 = str1.lastIndexOf("reference", 11)
const currentStr6 = str1.lastIndexOf("reference", 12)
๊ฒฐ๊ณผ๋ณด๊ธฐ
0
0
-1
-1
11
11

728x90

๋Œ“๊ธ€

๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๐Ÿฆ™

CSS
๊ด‘๊ณ  ์ค€๋น„์ค‘