encodeURIComponent
Encodes a URI component by replacing certain characters with UTF-8 escape sequences
Syntax
encodeURIComponent(uriComponent)Parameters
| Parameter | Type | Description |
|---|---|---|
| uriComponent | string | A string to be encoded as a URI component |
Return Value
A new string representing the provided string encoded as a URI component
Examples
console.log(encodeURIComponent('Hello World')); // 'Hello%20World'
console.log(encodeURIComponent('a=1&b=2')); // 'a%3D1%26b%3D2'function buildQuery(params: Record<string, string>) {
return Object.entries(params)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join('&');
}
console.log(buildQuery({ q: 'hello world', page: '1' }));const path = '/api/search?q=' + encodeURIComponent('foo bar&baz');
console.log(path); // '/api/search?q=foo%20bar%26baz'Understanding encodeURIComponent
The encodeURIComponent method in JavaScript encodes a URI component by replacing certain characters with UTF-8 escape sequences. It belongs to the window object and is one of the most widely used methods for working with window values in modern JavaScript and TypeScript applications.
The method signature is encodeURIComponent(uriComponent). It accepts 1 parameter: uriComponent. When called, it returns a new string representing the provided string encoded as a uri component. Understanding when and how to use encodeURIComponent() helps you write more expressive, readable code.
Common use cases for encodeURIComponent include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like window-decodeuricomponent, window-encodeuri, window-decodeuri, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for encodeURIComponent is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
decodeURIComponentDecodes a URI component previously created by encodeURIComponent or by a similar routine
encodeURIEncodes a URI by replacing certain characters with UTF-8 escape sequences, but preserves characters that are part of URI syntax
decodeURIDecodes a Uniform Resource Identifier previously created by encodeURI or by a similar routine
More Global / Window Methods
Other methods in the Global / Window object
Related Tools
More Global / Window Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.