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.
const url = "https://example.com/search?q=GoLinuxCloud Tutorial";
console.log("encodeURI:", encodeURI(url));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.
const query = "GoLinuxCloud Tutorial";
console.log("encodeURIComponent:", encodeURIComponent(query));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.
const query = "JavaScript encode URL";
const encodedQuery = encodeURIComponent(query);
const finalUrl = `https://example.com/search?q=${encodedQuery}`;
console.log("encoded-url:", finalUrl);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.
