---
title: String.prototype.indexOf()
slug: Web/JavaScript/Reference/Global_Objects/String/indexOf
tags:
  - JavaScript
  - Method
  - Prototype
  - Reference
  - String
translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf
---
<div>{{JSRef}}</div>

<p><strong><code>indexOf()</code></strong> 메서드는 호출한 {{jsxref("String")}} 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환합니다. 일치하는 값이 없으면 -1을 반환합니다. </p>

<div>{{EmbedInteractiveExample("pages/js/string-indexof.html")}}</div>



<div class="note">
<p><strong>참고:</strong> {{jsxref("Array")}}에서는 {{jsxref("Array.prototype.indexOf()")}} 메서드가 같은 역할을 합니다.</p>
</div>

<h2 id="구문">구문</h2>

<pre class="syntaxbox"><var>str</var>.indexOf(<var>searchValue</var>[, <var>fromIndex</var>])</pre>

<h3 id="매개변수">매개변수</h3>

<dl>
 <dt><code>searchValue</code></dt>
 <dd>찾으려는 문자열. 아무 값도 주어지지 않으면 <a href="https://tc39.github.io/ecma262/#sec-tostring">문자열 <code>"undefined"</code>를 찾으려는 문자열로 사용</a>합니다.</dd>
 <dt><code>fromIndex</code> {{optional_inline}}</dt>
 <dd>문자열에서 찾기 시작하는 위치를 나타내는 인덱스 값입니다. 어떤 정수값이라도 가능합니다. 기본값은 0이며, 문자열 전체를 대상으로 찾게 됩니다. 만약 <code>fromIndex </code>값이 음의 정수이면 전체 문자열을 찾게 됩니다. 만약 <code>fromIndex &gt;= str.length </code>이면, 검색하지 않고 바로 -1을 반환합니다. <code>searchValue</code>가 공백 문자열이 아니라면, <code>str.length</code>를 반환합니다.</dd>
</dl>

<h3 id="반환_값">반환 값</h3>

<p><code>searchValue</code>의 첫 번째 등장 인덱스. 찾을 수 없으면 -1.</p>

<h2 id="설명">설명</h2>

<p>문자열 내에 있는 문자들은 왼쪽에서 오른쪽 방향으로 순번이 매겨집니다. 제일 처음 문자는 0번째 순번(index)이며, <code>stringName </code>문자열의 마지막 문자의 순번 <code>stringName.length -1</code> 입니다. </p>

<pre class="brush: js">'Blue Whale'.indexOf('Blue');     // returns  0
'Blue Whale'.indexOf('Blute');    // returns -1
'Blue Whale'.indexOf('Whale', 0); // returns  5
'Blue Whale'.indexOf('Whale', 5); // returns  5
'Blue Whale'.indexOf('Whale', 7); // returns -1
'Blue Whale'.indexOf('');         // returns  0
'Blue Whale'.indexOf('', 9);      // returns  9
'Blue Whale'.indexOf('', 10);     // returns 10
'Blue Whale'.indexOf('', 11);     // returns 10</pre>

<p><code>indexOf()</code> 메서드는 대소문자를 구분합니다. 예를 들면, 아래 예제는 일치하는 문자열이 없으므로 <code>-1</code>을 반환합니다.</p>

<pre class="brush: js">'Blue Whale'.indexOf('blue'); // returns -1
</pre>

<h3 id="존재_여부_확인">존재 여부 확인</h3>

<p>'0'을 평가했을 때 <code>true</code>가 아니고, -1을 평가했을 때 <code>false</code>가 아닌 것에 주의해야 합니다. 따라서, 임의의 문자열에 특정 문자열이 있는지를 확인하는 올바른 방법은 다음과 같습니다.</p>

<pre class="brush: js">'Blue Whale'.indexOf('Blue') !== -1; // true
'Blue Whale'.indexOf('Bloe') !== -1; // false
</pre>

<h2 id="예제">예제</h2>

<h3 id="indexOf()_사용하기"><code>indexOf()</code> 사용하기</h3>

<p>아래 예제는 <code>"Brave new world"</code> 문자열의 위치를 확인하기 위해 <code>indexOf()</code>와 {{jsxref("String.prototype.lastIndexOf()", "lastIndexOf()")}} 를 사용하고 있습니다.</p>

<pre class="brush: js">var anyString = 'Brave new world';

console.log('The index of the first w from the beginning is ' + anyString.indexOf('w'));
// 첫번째 w 문자 위치는 8
console.log('The index of the first w from the end is ' + anyString.lastIndexOf('w'));
// 마지막 w 문자 위치는 10

console.log('The index of "new" from the beginning is ' + anyString.indexOf('new'));
// 첫번째 new 문자열 위치는 6
console.log('The index of "new" from the end is ' + anyString.lastIndexOf('new'));
// 마지막 new 문자열 위치는 6
</pre>

<h3 id="indexOf()와_대소문자_구분"><code>indexOf()</code>와 대소문자 구분</h3>

<p>아래 예제에서는 2개의 문자열 변수를 정의하고 있습니다. 이 변수들 내에 있는 문자열들은 모두 같지만 두 번째 변수에 포함되어 있는 문자열은 대문자를 포함하고 있습니다. 첫 번째 {{domxref("console.log()")}} 메서드의 결과값은 19입니다. 하지만, 두 번째 <code>console.log()</code> 메서드의 결과값은 <code>-1</code>입니다. 왜냐하면, indexOf() 메서드는 대소문자를 구분하기 때문에 <code>myCapString</code>에서 "<code>cheddar</code>" 문자열을 찾을 수 없기 때문입니다. </p>

<pre class="brush: js">var myString    = 'brie, pepper jack, cheddar';
var myCapString = 'Brie, Pepper Jack, Cheddar';

console.log('myString.indexOf("cheddar") is ' + myString.indexOf('cheddar'));
// 로그에 19를 출력합니다.
console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf('cheddar'));
// 로그에 -1을 출력합니다.
</pre>

<h3 id="indexOf()를_사용하여_문자열_내의_특정_문자_숫자_세기"><code>indexOf()</code>를 사용하여 문자열 내의 특정 문자 숫자 세기</h3>

<p>아래 예제는 <code>str </code>문자열에서 <code>e </code>문자의 총 숫자를 확인하는 프로그램입니다:</p>

<pre class="brush: js">var str = 'To be, or not to be, that is the question.';
var count = 0;
var pos = str.indexOf('e'); //pos는 4의 값을 가집니다.

while (pos !== -1) {
  count++;
  pos = str.indexOf('e', pos + 1); // 첫 번째 e 이후의 인덱스부터 e를 찾습니다.
}

console.log(count); // 로그에 4를 출력합니다.
</pre>

<h2 id="명세">명세</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES1')}}</td>
   <td>{{Spec2('ES1')}}</td>
   <td>Initial definition.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="브라우저_호환성">브라우저 호환성</h2>

<div>{{Compat("javascript.builtins.String.indexOf")}}</div>

<h2 id="같이_보기">같이 보기</h2>

<ul>
 <li>{{jsxref("String.prototype.charAt()")}}</li>
 <li>{{jsxref("String.prototype.lastIndexOf()")}}</li>
 <li>{{jsxref("String.prototype.split()")}}</li>
 <li>{{jsxref("Array.prototype.indexOf()")}}</li>
</ul>