1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
|
---
title: String.prototype.indexOf()
slug: Web/JavaScript/Reference/Global_Objects/String/indexOf
translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf
original_slug: Web/JavaScript/Referencia/Objectes_globals/String/indexOf
---
<div>{{JSRef}}</div>
<p>El mètode <code><strong>indexOf()</strong></code> retorna la primera posició dins el {{jsxref("String")}} des del que es crida a la qual es troba el valor proporcionat. Retorna -1 si no es troba el valor donat.</p>
<h2 id="Sintaxi">Sintaxi</h2>
<pre class="syntaxbox"><code><var>str</var>.indexOf(valorACercar[, posicioInicial]</code>)</pre>
<h3 id="Paràmetres">Paràmetres</h3>
<dl>
<dt><code>valorACercar</code></dt>
<dd>Un string que representa el valor a cercar.</dd>
<dt><code>posicioInicial</code> {{optional_inline}}</dt>
<dd>La posició a partir de la qual es cercarà dins la cadena. Pot ser qualsevol nombre sencer. El valor per defecte és <code>0</code>, indicant que es cercarà a tota la cadena. Si <code>posicioInicial</code><code> < 0</code> es cercarà a tota la cadena. Si <code>posicioInicial >= str.length</code>, no es cercarà a la cadena i es retornarà <code>-1</code> automàticament. Si <code>valorACercar</code> és una cadena buida es retornarà<code> str.length</code>.</dd>
</dl>
<h2 id="Descripció">Descripció</h2>
<p>Els caràcters de la cadena s'indexen d'esquerra a dreta. La posició del primer caràcter és <code>0</code>, i la posició de l'últim caràcter d'una cadena amb nom <code>stringName</code> és <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('', 9); // returns 9
'Blue Whale'.indexOf('', 10); // returns 10
'Blue Whale'.indexOf('', 11); // returns 10
</pre>
<h3 id="Distinció_entre_majúscules_i_minúscules">Distinció entre majúscules i minúscules</h3>
<p>El mètode <code>indexOf()</code> distingeix entre majúscules i minúscules. Per exemple, l'expressió següent retorna -1:</p>
<pre class="brush: js">'Blue Whale'.indexOf('blue'); // retorna -1
</pre>
<h3 id="Comprovar_troballes">Comprovar troballes</h3>
<p>Cal destacar que '0' no s'evalua a <code>true</code> i que '-1' no s'evalua a <code>false</code>. Tenim llavors que al comprovar si una cadena específica existeix dins una altra, la forma correcta de comprovar-ho seria:</p>
<pre class="brush: js">'Blue Whale'.indexOf('Blue') !== -1; // true
'Blue Whale'.indexOf('Bloe') !== -1; // false
</pre>
<h2 id="Exemples">Exemples</h2>
<h3 id="Utilitzar_indexOf()_i_lastIndexOf()">Utilitzar <code>indexOf()</code> i <code>lastIndexOf()</code></h3>
<p>L'exemple següent utilitza <code>indexOf()</code> i {{jsxref("String.prototype.lastIndexOf()", "lastIndexOf()")}} per a trobar valors dins la cadena <code>"Brave new world"</code>.</p>
<pre class="brush: js">var anyString = 'Brave new world';
console.log('La posicó de la primera w des del principi és ' + anyString.indexOf('w'));
// mostra 8
console.log('La posició de la primera w des del final és ' + anyString.lastIndexOf('w'));
// mostra 10
console.log('La posicó de "new" des del principi és ' + anyString.indexOf('new'));
// mostra 6
console.log('La posició de "new" des del final és ' + anyString.lastIndexOf('new'));
// mostra 6
</pre>
<h3 id="indexOf()_i_distinció_entre_majúscules_i_minúscules"><code>indexOf()</code> i distinció entre majúscules i minúscules</h3>
<p>L'exemple següent definteix dos variables de tipus cadena. The following example defines two string variables. The variables contain the same string except that the second string contains uppercase letters. The first {{domxref("console.log()")}} method displays 19. But because the <code>indexOf()</code> method is case sensitive, the string <code>"cheddar"</code> is not found in <code>myCapString</code>, so the second <code>console.log()</code> method displays -1.</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'));
// logs 19
console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf('cheddar'));
// logs -1
</pre>
<h3 id="Using_indexOf()_to_count_occurrences_of_a_letter_in_a_string">Using <code>indexOf()</code> to count occurrences of a letter in a string</h3>
<p>The following example sets <code>count</code> to the number of occurrences of the letter <code>e</code> in the string <code>str</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');
while (pos !== -1) {
count++;
pos = str.indexOf('e', pos + 1);
}
console.log(count); // displays 4
</pre>
<h2 id="Specifications">Specifications</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="Browser_compatibility">Browser compatibility</h2>
<div>{{CompatibilityTable}}</div>
<div id="compat-desktop">
<table class="compat-table">
<tbody>
<tr>
<th>Feature</th>
<th>Chrome</th>
<th>Firefox (Gecko)</th>
<th>Internet Explorer</th>
<th>Opera</th>
<th>Safari</th>
</tr>
<tr>
<td>Basic support</td>
<td>{{CompatVersionUnknown}}</td>
<td>{{CompatVersionUnknown}}</td>
<td>{{CompatVersionUnknown}}</td>
<td>{{CompatVersionUnknown}}</td>
<td>{{CompatVersionUnknown}}</td>
</tr>
</tbody>
</table>
</div>
<div id="compat-mobile">
<table class="compat-table">
<tbody>
<tr>
<th>Feature</th>
<th>Android</th>
<th>Chrome for Android</th>
<th>Firefox Mobile (Gecko)</th>
<th>IE Mobile</th>
<th>Opera Mobile</th>
<th>Safari Mobile</th>
</tr>
<tr>
<td>Basic support</td>
<td>{{CompatVersionUnknown}}</td>
<td>{{CompatVersionUnknown}}</td>
<td>{{CompatVersionUnknown}}</td>
<td>{{CompatVersionUnknown}}</td>
<td>{{CompatVersionUnknown}}</td>
<td>{{CompatVersionUnknown}}</td>
</tr>
</tbody>
</table>
</div>
<h2 id="See_also">See also</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>
|