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
|
---
title: encodeURIComponent()
slug: Web/JavaScript/Reference/Global_Objects/encodeURIComponent
translation_of: Web/JavaScript/Reference/Global_Objects/encodeURIComponent
---
<div>{{jsSidebar("Objects")}}</div>
<p>O método <code><strong>encodeURIComponent()</strong></code> codifica uma URI (Identificador recurso uniforme) substituindo cada ocorrência de determinados caracteres por um, dois, três, ou quatro seqüências de escape que representam a codificação UTF-8 do caractere (só será quatro seqüências de escape para caracteres compostos por dois caracteres "substituto").</p>
<h2 id="Syntaxe">Syntaxe</h2>
<pre class="syntaxbox">encodeURIComponent(str);</pre>
<h3 id="Parâmetros">Parâmetros</h3>
<dl>
<dt><code>str</code></dt>
<dd>String. Uma sequência URI.</dd>
</dl>
<h2 id="Descrição">Descrição</h2>
<p><code>encodeURIComponent</code> escapa todos os caracteres, exceto: alfabeto, dígitos decimais, <code>- _ . ! ~ * ' ( )</code></p>
<p>Note-se que um{{jsxref("URIError")}} será gerada se uma tentativas para codificar um substituto que não faz parte de um par de alta-baixa, por exemplo,</p>
<pre class="brush: js">// high-low par ok
console.log(encodeURIComponent('\uD800\uDFFF'));
// lone high surrogate throws "URIError: malformed URI sequence"
console.log(encodeURIComponent('\uD800'));
// lone low surrogate throws "URIError: malformed URI sequence"
console.log(encodeURIComponent('\uDFFF'));
</pre>
<p>Para previnir requisões inesperadas ao servidor, deve-se chamar <code>encodeURIComponent</code> ou qualquer parâmetro fornecido pelo usuário que será passado como parte da URI. Por exemplo, um usuário poderia digitar "<code>Thyme &time=again</code>" para uma variável <code>commentario</code>. Ao não usar <code>encodeURIComponent</code> nessa variável irá ser obetido <code>commentario=Thyme%20&time=again</code>. Note que o ampersa e o sinal de igual marcam um novo par de chave e valor. Então ao invés de ter um POST com a chave <code>commentario</code> igual a "<code>Thyme &time=again</code>", tem-se chaves em POST, uma igual a "<code>Thyme </code>" e outra (<code>time</code>) igual a <code>again</code>.</p>
<p>Para <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#application/x-www-form-urlencoded-encoding-algorithm"><code>application/x-www-form-urlencoded</code></a>, espaços são substituídos por '+', então pode-se querer seguir um <code>encodeURIComponent</code> substituição com uma substituição adicional de "%20" com "+".</p>
<p>Para ser mais rigoroso à aderência da <a class="external" href="http://tools.ietf.org/html/rfc3986">RFC 3986</a> (qual reserva !, ', (, ), e *), mesmo que esses caracteres não tenham usos formalizados de delimitação de URI, o seguinte pode ser usado com segurança:</p>
<pre class="brush: js">function ajustadoEncodeURIComponent (str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
</pre>
<h2 id="Exemplos">Exemplos</h2>
<p>O exemplo seguinte provê o encoding especial requerido pelo UTF-8 nos parâmetros <code>Content-Disposition</code> e <code>Link</code> no cabeçalho de uma Response (e.g., UTF-8 filenames):</p>
<pre class="brush: js">var fileName = 'my file(2).txt';
var header = "Content-Disposition: attachment; filename*=UTF-8''"
+ encodeRFC5987ValueChars(fileName);
console.log(header);
// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"
function encodeRFC5987ValueChars (str) {
return encodeURIComponent(str).
// Note that although RFC3986 reserves "!", RFC5987 does not,
// so we do not need to escape it
replace(/['()]/g, escape). // i.e., %27 %28 %29
replace(/\*/g, '%2A').
// The following are not required for percent-encoding per RFC5987,
// so we can allow for a little better readability over the wire: |`^
replace(/%(?:7C|60|5E)/g, unescape);
}
</pre>
<h2 id="Especificações">Especificações</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Especificação</th>
<th scope="col">Status</th>
<th scope="col">Comentario</th>
</tr>
<tr>
<td>{{SpecName('ES3')}}</td>
<td>{{Spec2('ES3')}}</td>
<td>Definição Inicial.</td>
</tr>
<tr>
<td>{{SpecName('ES5.1', '#sec-15.1.3.4', 'encodeURIComponent')}}</td>
<td>{{Spec2('ES5.1')}}</td>
<td> </td>
</tr>
<tr>
<td>{{SpecName('ES6', '#sec-encodeuricomponent-uricomponent', 'encodeURIComponent')}}</td>
<td>{{Spec2('ES6')}}</td>
<td> </td>
</tr>
</tbody>
</table>
<h2 id="Browser_compatibility">Compatibilidade com navegadores</h2>
<p>{{CompatibilityTable}}</p>
<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="Veja_também">Veja também</h2>
<ul>
<li>{{jsxref("decodeURI")}}</li>
<li>{{jsxref("encodeURI")}}</li>
<li>{{jsxref("decodeURIComponent")}}</li>
</ul>
|