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
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
-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
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
0
-1
-1
11
11
728x90
'Javascript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์๋ฐ์คํฌ๋ฆฝํธ : ๋ฌธ์์ด ๊ฒฐํฉ : ํ ํ๋ฆฟ ๋ฌธ์์ด (3) | 2022.08.17 |
---|---|
์๋ฐ์คํฌ๋ฆฝํธ : ๋ฌธ์์ด ๋ณ๊ฒฝ ๋ฉ์๋ : trim() / toUpperCase() / toLowerCase() (2) | 2022.08.17 |
์๋ฐ์คํฌ๋ฆฝํธ : ๋ฌธ์์ด ๋ณ๊ฒฝ ๋ฉ์๋ : slice() / substring() / substr() (6) | 2022.08.17 |
์๋ฐ์คํฌ๋ฆฝํธ : ์ ๊ท์ ํํ (6) | 2022.08.17 |
์๋ฐ์คํฌ๋ฆฝํธ : ๋ด์ฅํจ์ (8) | 2022.08.12 |
๋๊ธ