String.indexOf
indexOf()
๋ฉ์๋๋ String object
์ค์์ fromIndex
๊ฒ์์ ์์ํ๊ณ ๋ช
์๋ ๊ฐ์ด ์ฒ์ ์์๋๋ index๋ฅผ ๋ฐํํ๋ค. ๊ฐ์ด ์๋ ๊ฒฝ์ฐ -1
๋ฅผ ๋ฐํํ๋ค.
const sentence = '์ผ์๊ณ ์์ด๊ฐ ์ต๊ณ ์ผ!';
const searchTerm = '๊ณ ์์ด';
const indexOfFirst = sentence.indexOf(searchTerm); // 2
Syntax
str.indexOf(searchValue, [, fromIndex])
Parameters
searchValue
์ฐพ๊ธฐ ์ํ ๋ฌธ์์ด
๋ง์ฝ ์ฐพ๊ธฐ ์ํ ๋ฌธ์์ด์ด ์ ๊ณต๋์ง ์๋ ๊ฒฝ์ฐ, searchValue๋ "undefined"๊ฐ ๋๋ค.๐ฎ ๊ทธ๋ฆฌ๊ณ ์ด ๊ฐ์ str์์ ์ฐพ๋๋ค.
'undefined'.indexOf() -> 0์ ๋ฐํํ๋ค. searchValue๊ฐ ์์ด 'undefined'๋ฅผ ์ฐพ์ํ ๋๊น
'undefine'.indexOf() -> -1 d๊ฐ ๋น ์ก๋ค์.
fromIndex (optional)
ํํํ ์ ์๋ ์ ์์ ์ฐพ๊ธฐ ์์ํ๋ ์์น์ index์ด๋ค. ๊ธฐ๋ณธ๊ฐ์ 0์ด๋ค. fromIndex
๊ฐ์ด 0๋ณด๋ค ์๋ค๋ฉด 0๋ถํฐ str.length๊น์ง ๊ฒ์์ ์์ํ๋ค.
'hello world'.indexOf('o', -5) // fromIndex๊ฐ 0๋ณด๋ค ์๊ธฐ ๋๋ฌธ์ 0๋ถํฐ ์์ํ๋ค. ๋ฐํ๊ฐ์ 4 'hello world'.indexOf('o', 11) // fromIndex๊ฐ ์ ์ฒด ๋ฌธ์์ด์ length์ ๊ฐ๊ฑฐ๋ ํฌ๊ธฐ ๋๋ฌธ์ -1์ ๋ฐํํ๋ค.
Return value
searchValue๊ฐ ์กด์ฌํ๋ ์ฒซ๋ฒ์งธ index ๊ฐ์ด๋ ์กด์ฌํ์ง ์์ ๊ฒฝ์ฐ -1์ ๋ฐํํ๋ค.
searchValue๊ฐ ๋น๋ฌธ์์ด('')
์ผ ๊ฒฝ์ฐ ์ด์ํ ๊ฒฐ๊ณผ๊ฐ ๋ง๋ค์ด์ง๋ค. ๐ณ fromIndex ๊ฐ์ด ์๊ฑฐ๋ ๋ฌธ์์ด์ ์ ์ฒด ๊ธธ์ด๋ณด๋ค ์์ ๊ฐ์ index๋ผ๋ฉด ๋ฐํ๊ฐ์ fromIndex์ ๊ฐ๋ค. ๐ถ
'hello world'.indexOf(''); // 0 ์๋ต๋๋ฉด default ๊ฐ์ 0
'hello world'.indexOf('', 0); // 0
'hello world'.indexOf('', 3); // 3
'hello world'.indexOf('', 8); // 8
๊ทธ๋ฌ๋ fromIndex๊ฐ์ด ๋ฌธ์์ด์ ๊ธธ์ด์ ๊ฐ๊ฑฐ๋ ํด ๊ฒฝ์ฐ์ ๋ฌธ์์ด์ ๊ธธ์ด ๊ฐ์ ๋ฐํํ๋ค.
'hello world'.indexOf('', 11); // 11
'hello world'.indexOf('', 13); // 11
'hello world'.indexOf('', 22); // 11
์ ์์ ์๋ JS๋ ์ง์ ๋ ์์น์์ ๋น ๋ฌธ์์ด์ ๋ฐํํ๊ณ , ํ์์ ์์๋ ๋ฌธ์์ด๋์์ ๋น ๋ฌธ์์ด์ ๋ฐ๊ฒฌํ๋ค. ๋ญ์ง ๋ฌธ์์ด์ ๊ธธ์ด๋ณด๋ค ํฌ๋ฉด -1์ ๋ฐํํด์ผํ๋๋ฐ..
Description
๋ฌธ์์ด ๋ด์ ๋ฌธ์๋ค์ ์ผ์ชฝ์์ ์ค๋ฅธ์ชฝ ๋ฐฉํฅ์ผ๋ก index๊ฐ ๋งค๊ฒจ์ง๋ค.
indexOf()
๋ฉ์๋๋ ๋์๋ฌธ์๋ฅผ ๊ตฌ๋ถํ๋ค.
Checking occurrences
-1์ returnํ๋ค๋ณด๋ true, false๋ก ๋ช ์ํ๊ธฐ๊ฐ ์ข ๋ถํธํ๋ค. -1์ด falsy๊ฐ๋ ์๋๋๊น, ๊ทธ๋ฆฌ๊ณ 0์ ์กด์ฌํ์ง๋ง falsy๊ฐ์ด false๋ฅผ return ํ๋ค.
๊ทธ๋์ ์กด์ฌ์ฌ๋ถ๋ฅผ ํ์ธํ ๋๋ ์๋์ ๊ฐ์ด ๐
'๊ณ ์์ด๊ฐ ์งฑ์ด์!'.indexOf('๊ณ ์์ด') !== -1 // true
'๊ณ ์์ด๊ฐ ์งฑ์ด์ผ์'.indexOf('๋ฉ๋ญ์ด') !== -1 // false
Examples
case-sensitivity
๋์๋ฌธ์๋ฅผ ๊ตฌ๋ณํ๋ค.
'Cats are the best'.indexOf('Cats'); // 0
'Cats are the best'.indexOf('cats'); // -1
๋ฌธ์๊ฐ ๋ช ๊ฐ ์กด์ฌํ๋์ง ์ธ๊ธฐ
์ผ์ ์ด๋ฐ๊ฒ ์๋ค ์ฌ์ค Codewars์์ ์ด๋ฐ๋ฌธ์ ๋ฅผ ํผ๋ค๋ฉด ๋ฐฐ์ด๋ก ๋ฐ๊ฟ์.. ์ฃผ๋ก ํ์ง.. ๋ฌธ์์ด์ ์ ์งํ๋ฉด์ ํธ๋๊ฑด ์ ์
const str = '๊ณ ์์ด ํ๋ ๊ณ ์์ด ๋ ๊ณ ์์ด ์
๊ณ ์์ด ๋ท ๊ณ ์์ด ๋ค์ฏ';
let count = 0;
let position = str.indexOf('๊ณ ์์ด');
while (position !== -1) {
count++;
position = str.indexOf('๊ณ ์์ด', position + 1);
}
count; // 5 ๐ป
Last updated
Was this helpful?