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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
|
---
title: String.prototype.charAt()
slug: Web/JavaScript/Referencia/Objectes_globals/String/charAt
translation_of: Web/JavaScript/Reference/Global_Objects/String/charAt
---
<div>{{JSRef}}</div>
<p>El mètode <strong><code>charAt()</code></strong> retorna el caràcter especificat d'una cadena.</p>
<h2 id="Sintaxi">Sintaxi</h2>
<pre class="syntaxbox"><code><var>str</var>.charAt(posicio)</code></pre>
<h3 id="Paràmetres">Paràmetres</h3>
<dl>
<dt><code>posicio</code></dt>
<dd>Un nombre sencer entre 0 i la longitud de la cadena menys 1.</dd>
</dl>
<h2 id="Descripció">Descripció</h2>
<p>Els caràcters d'una cadena reben un nombre per la seva posició d'esquerra a dreta. La posició del primer caràcter és el 0 i la posició de l'últim caràcter d'una cadena anomenada <code>stringName</code> és <code>stringName.length - 1</code>. Si la <code>posicio</code> proporcionada està fora del rang vàlid JavaScript retornarà una cadena buida.</p>
<h2 id="Exemples">Exemples</h2>
<h3 id="Mostrar_caràcters_de_diferents_posicions_d'una_cadena">Mostrar caràcters de diferents posicions d'una cadena</h3>
<p>L'exemple següent mostra alguns caràcters a diferents posicions de la cadena <code>"Brave new world"</code>:</p>
<pre class="brush: js">var anyString = 'Brave new world';
console.log("El caràcter a la posició 0 és '" + anyString.charAt(0) + "'");
console.log("El caràcter a la posició 1 és '" + anyString.charAt(1) + "'");
console.log("El caràcter a la posició 2 és '" + anyString.charAt(2) + "'");
console.log("El caràcter a la posició 3 és '" + anyString.charAt(3) + "'");
console.log("El caràcter a la posició 4 és '" + anyString.charAt(4) + "'");
console.log("El caràcter a la posició 999 és '" + anyString.charAt(999) + "'");
</pre>
<p>Les línies anteriors mostren la sortida següent:</p>
<pre class="brush: js">El caràcter a la posició 0 és 'B'
El caràcter a la posició 1 és 'r'
El caràcter a la posició 2 és 'a'
El caràcter a la posició 3 és 'v'
El caràcter a la posició 4 és 'e'
El caràcter a la posició 999 és ''
</pre>
<h3 id="Obtenir_caràcters_sencers">Obtenir caràcters sencers</h3>
<p>El codi següent garanteix obtenir un caràcter sencer, fins i tot quan la cadena contingui caràcters que no formen part del pla bàsic multilingüístic.</p>
<pre class="brush: js">var str = 'A \uD87E\uDC04 Z'; // We could also use a non-BMP character directly
for (var i = 0, chr; i < str.length; i++) {
if ((chr = getWholeChar(str, i)) === false) {
continue;
}
// Adapt this line at the top of each loop, passing in the whole string and
// the current iteration and returning a variable to represent the
// individual character
console.log(chr);
}
function getWholeChar(str, i) {
var code = str.charCodeAt(i);
if (Number.isNaN(code)) {
return ''; // Position not found
}
if (code < 0xD800 || code > 0xDFFF) {
return str.charAt(i);
}
// High surrogate (could change last hex to 0xDB7F to treat high private
// surrogates as single characters)
if (0xD800 <= code && code <= 0xDBFF) {
if (str.length <= (i + 1)) {
throw 'High surrogate without following low surrogate';
}
var next = str.charCodeAt(i + 1);
if (0xDC00 > next || next > 0xDFFF) {
throw 'High surrogate without following low surrogate';
}
return str.charAt(i) + str.charAt(i + 1);
}
// Low surrogate (0xDC00 <= code && code <= 0xDFFF)
if (i === 0) {
throw 'Low surrogate without preceding high surrogate';
}
var prev = str.charCodeAt(i - 1);
// (could change last hex to 0xDB7F to treat high private
// surrogates as single characters)
if (0xD800 > prev || prev > 0xDBFF) {
throw 'Low surrogate without preceding high surrogate';
}
// We can pass over low surrogates now as the second component
// in a pair which we have already processed
return false;
}
</pre>
<p>En l'entorn de l'ECMAScript 2016, que soporta assignació desestructurada, es pot utilitzar el codi següent com a versió alternativa més flexibleenvironment which allows destructured assignment, the following is a more succinct and somewhat more flexible alternative in that it does incrementing for an incrementing variable automatically (if the character warrants it in being a surrogate pair).</p>
<pre class="brush: js">var str = 'A\uD87E\uDC04Z'; // We could also use a non-BMP character directly
for (var i = 0, chr; i < str.length; i++) {
[chr, i] = getWholeCharAndI(str, i);
// Adapt this line at the top of each loop, passing in the whole string and
// the current iteration and returning an array with the individual character
// and 'i' value (only changed if a surrogate pair)
console.log(chr);
}
function getWholeCharAndI(str, i) {
var code = str.charCodeAt(i);
if (Number.isNaN(code)) {
return ''; // Position not found
}
if (code < 0xD800 || code > 0xDFFF) {
return [str.charAt(i), i]; // Normal character, keeping 'i' the same
}
// High surrogate (could change last hex to 0xDB7F to treat high private
// surrogates as single characters)
if (0xD800 <= code && code <= 0xDBFF) {
if (str.length <= (i + 1)) {
throw 'High surrogate without following low surrogate';
}
var next = str.charCodeAt(i + 1);
if (0xDC00 > next || next > 0xDFFF) {
throw 'High surrogate without following low surrogate';
}
return [str.charAt(i) + str.charAt(i + 1), i + 1];
}
// Low surrogate (0xDC00 <= code && code <= 0xDFFF)
if (i === 0) {
throw 'Low surrogate without preceding high surrogate';
}
var prev = str.charCodeAt(i - 1);
// (could change last hex to 0xDB7F to treat high private surrogates
// as single characters)
if (0xD800 > prev || prev > 0xDBFF) {
throw 'Low surrogate without preceding high surrogate';
}
// Return the next character instead (and increment)
return [str.charAt(i + 1), i + 1];
}
</pre>
<h3 id="Fixing_charAt()_to_support_non-Basic-Multilingual-Plane_(BMP)_characters">Fixing <code>charAt()</code> to support non-Basic-Multilingual-Plane (BMP) characters</h3>
<p>While the example above may be more frequently useful for those wishing to support non-BMP characters (since it does not require the caller to know where any non-BMP character might appear), in the event that one <em>does</em> wish, in choosing a character by index, to treat the surrogate pairs within a string as the single characters they represent, one can use the following:</p>
<pre class="brush: js">function fixedCharAt(str, idx) {
var ret = '';
str += '';
var end = str.length;
var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
while ((surrogatePairs.exec(str)) != null) {
var li = surrogatePairs.lastIndex;
if (li - 2 < idx) {
idx++;
} else {
break;
}
}
if (idx >= end || idx < 0) {
return '';
}
ret += str.charAt(idx);
if (/[\uD800-\uDBFF]/.test(ret) && /[\uDC00-\uDFFF]/.test(str.charAt(idx + 1))) {
// Go one further, since one of the "characters" is part of a surrogate pair
ret += str.charAt(idx + 1);
}
return ret;
}
</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.4', 'String.prototype.charAt')}}</td>
<td>{{Spec2('ES5.1')}}</td>
<td> </td>
</tr>
<tr>
<td>{{SpecName('ES6', '#sec-string.prototype.charat', 'String.prototype.charAt')}}</td>
<td>{{Spec2('ES6')}}</td>
<td> </td>
</tr>
<tr>
<td>{{SpecName('ESDraft', '#sec-string.prototype.charat', 'String.prototype.charAt')}}</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.indexOf()")}}</li>
<li>{{jsxref("String.prototype.lastIndexOf()")}}</li>
<li>{{jsxref("String.prototype.charCodeAt()")}}</li>
<li>{{jsxref("String.prototype.codePointAt()")}}</li>
<li>{{jsxref("String.prototype.split()")}}</li>
<li>{{jsxref("String.fromCodePoint()")}}</li>
<li><a href="https://mathiasbynens.be/notes/javascript-unicode">JavaScript has a Unicode problem – Mathias Bynens</a></li>
</ul>
|