JavaScript URL Encode with encodeURI and encodeURIComponent

Learn JavaScript URL encoding with encodeURI() and encodeURIComponent(), including full URL encoding, query parameter encoding, and template literal examples.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

JavaScript URL Encode with encodeURI and encodeURIComponent

URL encoding converts text into a safe format for URLs. It is essential when a query string, path segment, or parameter value contains spaces or special characters that must be escaped before the browser sends the request.

JavaScript gives you encodeURI() for full URLs and encodeURIComponent() for individual parts of a URL. When you build the URL dynamically, JavaScript template literals make the final string easier to read.

Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.


Method 1: Use encodeURI() for a full URL

encodeURI() keeps URL separators such as ?, &, and / intact while encoding spaces and other unsafe characters.

javascript
const url = "https://example.com/search?q=GoLinuxCloud Tutorial";
console.log("encodeURI:", encodeURI(url));
Output

You should see one line logging encodeURI: https://example.com/search?q=GoLinuxCloud%20Tutorial.

Use this when the whole URL is already structured and you only need to make it safe for transmission.


Method 2: Use encodeURIComponent() for a query value

encodeURIComponent() escapes characters such as spaces, &, and = so the value can be inserted safely into a query string or path segment.

javascript
const query = "GoLinuxCloud Tutorial";
console.log("encodeURIComponent:", encodeURIComponent(query));
Output

You should see one line logging encodeURIComponent: GoLinuxCloud%20Tutorial.

Use this when you are preparing a single parameter value, not the full URL.


Method 3: Build a URL with template literals

Template literals make dynamic URL assembly easier to read, especially when you are inserting encoded values into a search URL.

javascript
const query = "JavaScript encode URL";
const encodedQuery = encodeURIComponent(query);
const finalUrl = `https://example.com/search?q=${encodedQuery}`;

console.log("encoded-url:", finalUrl);
Output

You should see one line logging encoded-url: https://example.com/search?q=JavaScript%20encode%20URL.

This is the pattern to use in search pages, filter links, and any code that creates URLs from user input.


Summary

JavaScript URL encoding is straightforward once you choose the right method. Use encodeURI() for a complete URL, encodeURIComponent() for a query value or path fragment, and template literals when you need to assemble the final URL cleanly.


Official documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …