Revision 498383 of encodeURIComponent()

  • Revision slug: Web/JavaScript/Reference/Global_Objects/encodeURIComponent
  • Revision title: encodeURIComponent
  • Revision id: 498383
  • Created:
  • Creator: fscholz
  • Is current revision? No
  • Comment cleanup
Tags: 

Revision Content

{{JSObjectsQLAlpha()}}

Summary

The encodeURIComponent() method encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Syntax

encodeURIComponent(str);

Parameters

str
String. A component of a URI.

Description

encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )

Note that an error will be thrown if one attempts to encode a surrogate which is not part of a high-low pair, e.g.,

alert(encodeURIComponent('\uD800\uDFFF')); // high-low pair ok
alert(encodeURIComponent('\uD800')); // lone high surrogate throws "URIError: malformed URI sequence"
alert(encodeURIComponent('\uDFFF')); // lone low surrogate throws "URIError: malformed URI sequence"

To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST comment key equal to "Thyme &time=again", you have two POST keys, one equal to "Thyme " and another (time) equal to again.

For application/x-www-form-urlencoded (POST), spaces are to be replaced by '+', so one may wish to follow a encodeURIComponent replacement with an additional replacement of "%20" with "+".

To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

function fixedEncodeURIComponent (str) {
  return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}

Examples

The following example provides the special encoding required within UTF-8 Content-Disposition and Link server response header parameters (e.g., UTF-8 filenames):

var fileName = 'my file(2).txt';
var header = "Content-Disposition: attachment; filename*=UTF-8''" + encodeRFC5987ValueChars(fileName);
console.log(header); // 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);
}

Specifications

Specification Status Comment
ECMAScript 3rd Edition. Standard Initial definition.
{{SpecName('ES5.1', '#sec-15.1.3.4', 'encodeURIComponent')}} {{Spec2('ES5.1')}}  
{{SpecName('ES6', '#sec-encodeuricomponent-uricomponent', 'encodeURIComponent')}} {{Spec2('ES6')}}  

Browser compatibility

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }}

See also

  • {{jsxref("Global_Objects/decodeURI", "decodeURI")}}
  • {{jsxref("Global_Objects/encodeURI", "encodeURI")}}
  • {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent")}}

Revision Source

<div>
 {{JSObjectsQLAlpha()}}</div>
<h2 id="Summary" name="Summary">Summary</h2>
<p>The <code><strong>encodeURIComponent()</strong></code> method encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).</p>
<h2 id="Syntax" name="Syntax">Syntax</h2>
<pre class="syntaxbox">
encodeURIComponent(str);</pre>
<h3 id="Parameters" name="Parameters">Parameters</h3>
<dl>
 <dt>
  <code>str</code></dt>
 <dd>
  String. A component of a URI.</dd>
</dl>
<h2 id="Description" name="Description">Description</h2>
<p><code>encodeURIComponent</code> escapes all characters except the following: alphabetic, decimal digits, <code>- _ .&nbsp;! ~ * ' ( )</code></p>
<p>Note that an error will be thrown if one attempts to encode a surrogate which is not part of a high-low pair, e.g.,</p>
<pre class="brush: js">
alert(encodeURIComponent('\uD800\uDFFF')); // high-low pair ok
alert(encodeURIComponent('\uD800')); // lone high surrogate throws "URIError: malformed URI sequence"
alert(encodeURIComponent('\uDFFF')); // lone low surrogate throws "URIError: malformed URI sequence"
</pre>
<p>To avoid unexpected requests to the server, you should call <code>encodeURIComponent</code> on any user-entered parameters that will be passed as part of a URI. For example, a user could type "<code>Thyme &amp;time=again</code>" for a variable <code>comment</code>. Not using <code>encodeURIComponent</code> on this variable will give <code>comment=Thyme%20&amp;time=again</code>. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST <code>comment</code> key equal to "<code>Thyme &amp;time=again</code>", you have two POST keys, one equal to "<code>Thyme </code>" and another (<code>time</code>) equal to <code>again</code>.</p>
<p>For <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> (POST), spaces are to be replaced by '+', so one may wish to follow a <code>encodeURIComponent</code> replacement with an additional replacement of "%20" with "+".</p>
<p>To be more stringent in adhering to <a class="external" href="http://tools.ietf.org/html/rfc3986">RFC 3986</a> (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:</p>
<pre class="brush: js">
function fixedEncodeURIComponent (str) {
  return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}
</pre>
<h2 id="See_also" name="See_also">Examples</h2>
<p>The following example provides the special encoding required within UTF-8 <code>Content-Disposition</code> and <code>Link</code> server response header parameters (e.g., UTF-8 filenames):</p>
<pre class="brush: js" name="See_also">
var fileName = 'my file(2).txt';
var header = "Content-Disposition: attachment; filename*=UTF-8''" + encodeRFC5987ValueChars(fileName);
console.log(header); // Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt


function encodeRFC5987ValueChars (str) {
&nbsp;&nbsp;&nbsp; return encodeURIComponent(str).
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Note that although RFC3986 reserves "!", RFC5987 does not, so we do not need to escape it
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; replace(/['()]/g, escape). // i.e., %27 %28 %29
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; replace(/\*/g, '%2A').
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // The following are not required for percent-encoding per RFC5987, so we can allow for a little better readability over the wire: |`^
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; replace(/%(?:7C|60|5E)/g, unescape);
}
</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>ECMAScript 3rd Edition.</td>
   <td>Standard</td>
   <td>Initial definition.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.1.3.4', 'encodeURIComponent')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>&nbsp;</td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-encodeuricomponent-uricomponent', 'encodeURIComponent')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>&nbsp;</td>
  </tr>
 </tbody>
</table>
<h2 id="Browser_compatibility">Browser compatibility</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="See_Also" name="See_Also">See also</h2>
<ul>
 <li>{{jsxref("Global_Objects/decodeURI", "decodeURI")}}</li>
 <li>{{jsxref("Global_Objects/encodeURI", "encodeURI")}}</li>
 <li>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent")}}</li>
</ul>
<!-- languages({
	"fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Fonctions_globales/encodeURIComponent",
	"zh-cn":"zh-cn/JavaScript/Reference/Global_Objects/encodeURIComponent"
}) -->
Revert to this revision