Skip to main content

URL Encode in JavaScript — Free Online Tool + Code Examples

Learn how to URL encode strings in JavaScript using encodeURIComponent(). Use our free online URL encoder and copy ready-to-use JavaScript code examples.

How to URL Encode in JavaScript

JavaScript provides two built-in functions for URL encoding: encodeURIComponent() and encodeURI(). The key difference is that encodeURIComponent() encodes everything except letters, digits, and - _ . ! ~ * ' ( ), while encodeURI() preserves URI-special characters like : / ? # [ ] @.

For most use cases — query parameters, form data, API requests — you should use encodeURIComponent(). It is the safer choice because it encodes characters that could break URL structure when used inside parameter values.

encodeURIComponent() Examples

// Encode a search query for a URL parameter
const query = 'hello world & goodbye';
const encoded = encodeURIComponent(query);
console.log(encoded);
// Output: hello%20world%20%26%20goodbye

// Build a complete URL with encoded parameters
const base = 'https://api.example.com/search';
const url = `${base}?q=${encodeURIComponent(query)}&lang=en`;
console.log(url);
// https://api.example.com/search?q=hello%20world%20%26%20goodbye&lang=en

// Encode special characters
encodeURIComponent('price=100€');  // price%3D100%E2%82%AC
encodeURIComponent('path/to/file'); // path%2Fto%2Ffile
encodeURIComponent('name=John Doe&age=30'); // name%3DJohn%20Doe%26age%3D30

encodeURI() vs encodeURIComponent()

InputencodeURI()encodeURIComponent()
hello worldhello%20worldhello%20world
a=1&b=2a=1&b=2a%3D1%26b%3D2
https://example.comhttps://example.comhttps%3A%2F%2Fexample.com

When to Use Each Function

  • encodeURIComponent() — Use for encoding individual parameter values, form fields, or any string that will be placed inside a URL component.
  • encodeURI() — Use only when encoding a complete URI where you want to preserve the URL structure (protocol, slashes, query delimiters).
  • URLSearchParams — Modern alternative for building query strings that handles encoding automatically.

Modern Alternative: URLSearchParams

const params = new URLSearchParams({
    q: 'hello world & goodbye',
    lang: 'en',
    page: '1'
});
console.log(params.toString());
// q=hello+world+%26+goodbye&lang=en&page=1

// Use with fetch()
fetch(`https://api.example.com/search?${params}`);

Try URL Encoder/Decoder Free

Encode and decode URLs.

Use URL Encoder/Decoder →