Question
How can I safely encode a URL in JavaScript so it can be included as a value inside a GET query string?
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;
Should the myUrl variable be encoded on the second line before being appended to myOtherUrl?
Short Answer
By the end of this page, you will understand how URL encoding works in JavaScript, when to use encodeURIComponent() instead of encodeURI(), and how to safely place one URL inside another URL's query string without breaking the final address.
Concept
When you place data inside a URL, certain characters have special meaning.
For example:
?starts the query string&separates query parameters=separates a parameter name from its value#starts a fragment
If you insert a full URL directly into a query parameter without encoding it, those special characters will be interpreted as part of the outer URL instead of as plain text.
In the question example, this is the problem:
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;
This produces:
http://example.com/index.html?url=http://example.com/index.html?param=1&anotherParam=2
The browser or server may read that as:
url = http://example.com/index.html?param=1anotherParam = 2
That is not what you intended.
To safely include one URL as the value of another URL's query parameter, use encodeURIComponent():
Mental Model
Think of a URL like a sentence with punctuation.
If you want to place one full sentence inside another sentence, you cannot leave all the punctuation unchanged, or the outer sentence becomes confusing.
encodeURIComponent() works like wrapping the inner sentence so the outer sentence treats it as data, not as instructions.
In this example:
- The outer URL is the container
- The
urlparameter is a labelled box - The inner URL is the value being placed inside the box
If you do not encode it, characters like ? and & spill out of the box and start affecting the outer URL.
Encoding keeps everything inside the box.
Syntax and Examples
The most common function for query parameter values is:
encodeURIComponent(value)
Basic example
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);
console.log(myOtherUrl);
Output:
http://example.com/index.html?url=http%3A%2F%2Fexample.com%2Findex.html%3Fparam%3D1%26anotherParam%3D2
This is safe because the embedded URL is now treated as a single parameter value.
Decoding later
If you receive that parameter later and want the original URL back:
var encoded = encodeURIComponent("http://example.com/index.html?param=1&anotherParam=2");
var decoded = decodeURIComponent(encoded);
console.log(decoded);
Output:
http://example.com/index.html?param=1&anotherParam=2
vs
Step by Step Execution
Consider this code:
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);
console.log(myOtherUrl);
Step 1: Store the inner URL
myUrl contains:
http://example.com/index.html?param=1&anotherParam=2
Step 2: Encode the inner URL
encodeURIComponent(myUrl) transforms special characters:
http%3A%2F%2Fexample.com%2Findex.html%3Fparam%3D1%26anotherParam%3D2
Important examples:
:becomes%3A/becomes%2F?becomes%3F=becomes%3D
Real World Use Cases
Encoding URLs inside query strings appears in many real applications.
Redirect links
A login page often receives a redirect parameter:
var redirectTo = "/dashboard?tab=profile";
var loginUrl = "/login?redirect=" + encodeURIComponent(redirectTo);
OAuth and authentication flows
Many authentication systems send a callback URL:
var callbackUrl = "https://myapp.com/auth/callback?source=google";
var authUrl = "https://provider.com/login?callback=" + encodeURIComponent(callbackUrl);
Sharing filtered pages
A page might include the current search URL inside another link:
var currentPage = "https://shop.com/products?category=books&sort=price";
var shareUrl = "/share?target=" + encodeURIComponent(currentPage);
API requests
Some APIs accept a URL to crawl, preview, or shorten:
var targetUrl = ;
apiUrl = + (targetUrl);
Real Codebase Usage
In real codebases, developers usually avoid manual string building when possible.
Common pattern: encode parameter values
var url = "/api/preview?url=" + encodeURIComponent(targetUrl);
This is simple and works well for one or two parameters.
Common pattern: use URLSearchParams
var params = new URLSearchParams({
url: targetUrl,
lang: "en",
mode: "full"
});
var requestUrl = "/api/preview?" + params.toString();
This reduces mistakes and automatically encodes values.
Validation before encoding
Developers often check that a value exists before adding it:
function buildUrl(baseUrl, targetUrl) {
if (!targetUrl) {
return baseUrl;
}
return baseUrl + "?url=" + encodeURIComponent(targetUrl);
}
This is a simple guard clause.
Common Mistakes
1. Using encodeURI() for a query parameter value
Broken example:
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + encodeURI(myUrl);
Why it is wrong:
encodeURI()does not encode characters like?and&in the way needed for a parameter value- The outer query string can still break
Use this instead:
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);
2. Not encoding at all
Broken example:
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;
Why it is wrong:
- The embedded URL may create extra parameters accidentally
3. Encoding the whole final URL with encodeURIComponent()
Comparisons
| Method | Best use | Encodes ? and & | Good for nested query parameter values? |
|---|---|---|---|
encodeURI() | Encoding a complete URL | No | No |
encodeURIComponent() | Encoding one URL part or parameter value | Yes | Yes |
URLSearchParams | Building query strings safely | Yes, automatically for values | Yes |
Example comparison
var value = "http://example.com/index.html?param=1&anotherParam=2";
console.log(encodeURI(value));
.((value));
Cheat Sheet
Quick rule
If a value is going inside a query parameter, use:
encodeURIComponent(value)
Correct pattern
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);
Decode later if needed
var original = decodeURIComponent(encodedValue);
When to use each
encodeURI(fullUrl)- Use for a full URL
- Keeps URL structure characters mostly intact
encodeURIComponent(value)- Use for a query parameter value, path segment, or other URL part
- Encodes reserved characters such as
?,&,=,/,:
Safer modern alternative
FAQ
Should I encode the whole URL or just the parameter value?
Encode just the parameter value when inserting it into another URL's query string.
What is the difference between encodeURI() and encodeURIComponent()?
encodeURI() is for a full URL. encodeURIComponent() is for one piece of a URL, such as a query parameter value.
Why does an unencoded URL break a query string?
Because characters like ? and & are treated as separators in the outer URL.
Can I use URLSearchParams instead of encodeURIComponent()?
Yes. URLSearchParams is a great modern way to build query strings and handles encoding automatically.
Do I need to decode the value later?
Usually yes, if you want the original readable value back.
Is replacing spaces with %20 enough?
No. Many other characters must also be encoded, such as &, ?, =, /, and .
Mini Project
Description
Build a small JavaScript utility that creates a redirect link for a login page. The app should take a destination URL, safely place it inside a redirect query parameter, and produce a final URL that can be used in a real application. This demonstrates how to safely embed one URL inside another without breaking query parsing.
Goal
Create a function that generates a valid login URL containing an encoded redirect destination.
Requirements
- Write a function that accepts a destination URL as input.
- Return a login URL with the destination stored in a
redirectquery parameter. - Ensure the destination URL is safely encoded.
- Show an example destination URL that already contains its own query string.
- Demonstrate how to decode the redirect value back to the original URL.
Keep learning
Related questions
Adding Table Rows with jQuery: append(), Limits, and Best Practices
Learn how to add table rows in jQuery using append(), what elements are allowed in tables, and safer ways to build rows dynamically.
Bower vs npm: What’s the Difference in JavaScript Package Management?
Learn the plain difference between Bower and npm, how each manages packages, and why npm replaced Bower in most JavaScript projects.
Can `(a == 1 && a == 2 && a == 3)` Ever Be True in JavaScript?
Learn how JavaScript type coercion, loose equality, and custom object conversion can make `a == 1 && a == 2 && a == 3` true.