Question

How to Encode a URL in JavaScript for Query Strings

javascripturlencodeurlencode

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=1
  • anotherParam = 2

That is not what you intended.

To safely include one URL as the value of another URL's query parameter, use encodeURIComponent():

var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);

This converts special characters into encoded forms such as:

  • : becomes %3A
  • / becomes %2F
  • ? becomes %3F
  • & becomes %26

Why this matters in real programming:

  • APIs often send callback URLs as parameters
  • Redirect URLs must be safely embedded in links
  • Search filters and nested query strings break easily without encoding
  • Encoding helps preserve the exact original value

The key rule is simple:

  • Use encodeURIComponent() for a query parameter value
  • Use encodeURI() only when encoding a complete URL that should keep its structural characters intact

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 url parameter 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.

Take Quiz

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

encodeURI() vs encodeURIComponent()

var url = "http://example.com/index.html?param=1&anotherParam=2";

console.log(encodeURI(url));
console.log(encodeURIComponent(url));

encodeURI(url) keeps URL structure characters like :, /, ?, and & mostly intact.

encodeURIComponent(url) encodes those characters too, which is exactly what you want when the URL is being used as a parameter value.

Modern approach with URLSearchParams

var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var params = new URLSearchParams({ url: myUrl });
var myOtherUrl = "http://example.com/index.html?" + params.toString();

console.log(myOtherUrl);

This automatically handles encoding for query parameters.

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
  • & becomes %26

Step 3: Append it to the outer URL

The final string becomes:

http://example.com/index.html?url=http%3A%2F%2Fexample.com%2Findex.html%3Fparam%3D1%26anotherParam%3D2

Step 4: Result

Now the outer URL has exactly one query parameter named url, and its value is the full inner URL.

What would happen without encoding?

Without encoding:

var myOtherUrl = "http://example.com/index.html?url=" + myUrl;

Result:

http://example.com/index.html?url=http://example.com/index.html?param=1&anotherParam=2

The outer query string may now be interpreted as:

  • url = http://example.com/index.html?param=1
  • anotherParam = 2

So the embedded URL gets broken into multiple parameters.

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 = "https://news.com/article?id=42&ref=homepage";
var apiUrl = "/api/preview?url=" + encodeURIComponent(targetUrl);

Analytics and tracking

Tracking systems often store the source page URL inside a request parameter.

Take Quiz

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.

Decoding on the receiving side

When a backend or frontend reads the parameter, it often decodes it back before use.

Configuration and redirects

Applications frequently pass around return URLs, deep links, or callback URLs through config-driven routing. Proper encoding prevents subtle bugs that are hard to debug later.

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()

Broken example:

var myOtherUrl = encodeURIComponent("http://example.com/index.html?url=" + myUrl);

Why it is wrong:

  • This encodes the outer URL too
  • The result is no longer a normal usable URL string

Usually, only encode the parameter value.

4. Double encoding

Broken example:

var encoded = encodeURIComponent(myUrl);
var doubleEncoded = encodeURIComponent(encoded);

Why it is wrong:

  • % becomes %25
  • Decoding becomes confusing
  • URLs may stop working unless decoded the same number of times

5. Forgetting to decode when reading the value

If you receive an encoded value and display or process it directly, it may still contain %3A, %2F, and similar sequences.

Use:

decodeURIComponent(value)

when you need the original text.

6. Manually replacing only some characters

Broken example:

var unsafe = myUrl.replace(/&/g, "%26");

Why it is wrong:

  • URLs contain many special characters, not just &
  • Manual replacement is incomplete and fragile

Comparisons

MethodBest useEncodes ? and &Good for nested query parameter values?
encodeURI()Encoding a complete URLNoNo
encodeURIComponent()Encoding one URL part or parameter valueYesYes
URLSearchParamsBuilding query strings safelyYes, automatically for valuesYes

Example comparison

var value = "http://example.com/index.html?param=1&anotherParam=2";

console.log(encodeURI(value));
console.log(encodeURIComponent(value));

encodeURI(value) result keeps separators more readable, but that is exactly why it is unsafe for embedding as a query parameter value.

encodeURIComponent(value) fully protects the value for use inside another query string.

Manual concatenation vs URLSearchParams

ApproachProsCons
Manual string concatenationSimple for tiny casesEasy to forget encoding
URLSearchParamsSafer, cleaner, scalableSlightly more verbose

For modern JavaScript, URLSearchParams is often the safest choice when building query strings with multiple parameters.

Take Quiz

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

var params = new URLSearchParams({ url: myUrl });
var finalUrl = "http://example.com/index.html?" + params.toString();

Common pitfalls

  • Do not append raw URLs into query strings
  • Do not use encodeURI() for a parameter value
  • Do not double encode unless you truly mean to
  • Do not manually replace only one or two characters

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 :.

What happens if I encode twice?

The value becomes double encoded, which can break decoding and produce incorrect URLs.

Take Quiz

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 redirect query 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.
Take Quiz

Keep learning

Related questions

View more