๋ฌธ์์ด ๋ฉ์๋ : indexOf() / lastIndexOf()
์ด๋ฒ ํฌ์คํ
์์๋ ๋ฌธ์์ด ๋ฉ์๋ ์ค indexOf์ lastIndexOf์ ๋ํด ๋ค๋ค๋ณด๋๋ก ํ๊ฒ ์ต๋๋ค.
indexOf()
๋ฌธ์์ด์์ ํน์ ๋ฌธ์์ด์ ์ฒซ๋ฒ์งธ๋ก ์์๋๋ ์์น๋ฅผ ์์์๋ถํฐ ์ฐพ๊ณ , ๊ทธ ์์น๋ฅผ ์ซ์๋ก ๋ฐํํ๋ค.
"๋ฌธ์์ด".indexOf(๊ฒ์๊ฐ)
"๋ฌธ์์ด".indexOf(๊ฒ์๊ฐ, ์์น๊ฐ)
์ฐพ๋ ๋ฌธ์์ด์ด ์์ผ๋ฉด -1์ ๋ฆฌํด(์ถ๋ ฅ)ํ๋ค.
๋ฌธ์์ด์ ์ฐพ์ ๋ ๋์๋ฌธ์๋ฅผ ๊ตฌ๋ถํ๋ค.
์ฝ๋ ๋ณด๊ธฐ
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 : reference๋ 11๋ถํฐ ์์ํ๊ธฐ ๋๋ฌธ์ 0~11 ์ค ์๋ฌด ์ซ์๋ ์
๋ ฅํด๋ 11 ์ถ๋ ฅ
const currentStr11 = str1.indexOf("reference", 1); // 11
const currentStr12 = str1.indexOf("reference", 11); // 11
const currentStr13 = str1.indexOf("reference", 12); // -1
lastIndexOf()
๋ฌธ์์ด์์ ํน์ ๋ฌธ์์ด์ ์ฒซ๋ฒ์งธ๋ก ์์๋๋ ์์น๋ฅผ ๋ค์์๋ถํฐ ์ฐพ๊ณ , ๊ทธ ์์น๋ฅผ ์ซ์๋ก ๋ฐํํ๋ค.
"๋ฌธ์์ด".lastIndexOf(๊ฒ์๊ฐ)
"๋ฌธ์์ด".lastIndexOf(๊ฒ์๊ฐ, ์์น๊ฐ)
์ฐพ๋ ๋ฌธ์์ด์ด ์์ผ๋ฉด -1์ ๋ฆฌํด(์ถ๋ ฅ)ํ๋ค.
๋ฌธ์์ด์ ์ฐพ์ ๋ ๋์๋ฌธ์๋ฅผ ๊ตฌ๋ถํ๋ค.
์ฝ๋ ๋ณด๊ธฐ
const str1 = "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 : ๋ค์์๋ถํฐ ์์ํด์ ์ฒ์ ๋์ค๋ 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
'JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JavaScript] ๋์๋ฌธ์ ๋ณ๊ฒฝ - toUpperCase() & toLowerCase() (3) | 2022.08.17 |
---|---|
[JavaScript] ์ ๊ท ํํ์ ์์๋ณด๊ธฐ (10) | 2022.08.16 |
[JavaScript] ๋ฌธ์์ด ๋ฉ์๋ ์์๋ณด๊ธฐ (8) | 2022.08.16 |
[JavaScript] ๋ด์ฅ ํจ์ (7) | 2022.08.13 |
[JavaScript] ๋ฐฐ์ด ๋ฉ์๋ ์์๋ณด๊ธฐ (8) | 2022.08.11 |
๋๊ธ