Skip to content
Subscribe to RSS Find me on GitHub Follow me on Twitter

How to Pass Parameters in a URL in JavaScript

How to Pass Parameters in a URL in JavaScript

Have you ever noticed how some website addresses look like this: https://example.com/search?q=pizza&page=2? That question mark and the strange codes after it are called URL parameters (or query parameters). They’re a simple way to send extra information to a webpage. For example, the q=pizza part tells the search page what you’re looking for, and page=2 tells it which results page to show.

As a beginner, you might be tempted to build these URLs by hand—adding strings together with plus signs and hoping for the best. But there’s a much safer, cleaner way to do it using modern JavaScript tools. In this guide, you’ll learn how to use the URL and URLSearchParams objects to build and read URL parameters like a pro. These built-in tools handle all the tricky details—like special characters and formatting—so you don’t have to worry about them.

By the end of this tutorial, you’ll be able to create URLs with custom parameters and extract those parameters from the browser’s address bar in your own projects. Let’s get started!

Why URL Parameters Matter

URL parameters are everywhere on the web. They power search engines, filter products in online stores, track user preferences, and much more. When you build a website that needs to remember what a user is doing—like what they searched for or which category they clicked—URL parameters are often the simplest way to store that information.

The good news is that JavaScript has built-in tools to make this easy. The URL object helps you work with entire web addresses, while URLSearchParams focuses specifically on the parameter part (everything after the ?). Together, they form a powerful duo that eliminates the need for manual string manipulation, which is error-prone and can create security issues.

The Old Way (And Why You Should Avoid It)

Before we dive into the modern approach, let’s look at what many beginners try first. Imagine you want to add a search term to a URL:

// Don't do this!
const baseUrl = 'https://example.com/search';
const searchTerm = 'web development';
const url = baseUrl + '?q=' + searchTerm;
console.log(url);

This seems fine until you search for something with spaces or special characters. What happens if searchTerm is "pizza & pasta"? You’d get a malformed URL that breaks your page. You’d need to manually escape characters, check for existing question marks, and handle a dozen other edge cases. It’s a headache waiting to happen.

The modern approach handles all of this automatically. It’s safer, easier to read, and less likely to cause bugs.

Step-by-Step: Building URLs with Parameters

Let’s walk through the process of creating a URL with parameters. These steps work in all modern browsers and require no external libraries.

Step 1: Create a URL Object

First, you need a base URL. This is the main address of your page before any parameters are added. You create a URL object by using the new URL() constructor and passing in your base address.

const url = new URL('https://example.com/search');

This creates a URL object that represents https://example.com/search. Think of it as a container that holds all the parts of a web address—the protocol (https://), the domain (example.com), the path (/search), and eventually, our parameters.

Step 2: Add Parameters Using searchParams

Every URL object has a property called searchParams. This is a special URLSearchParams object that manages all your parameters. You can add, change, or remove parameters using simple methods.

url.searchParams.set('q', 'web dev');
url.searchParams.set('page', '2');

The set() method takes two arguments: the parameter name ('q') and its value ('web dev'). If the parameter already exists, set() will update it. If it doesn’t exist, it will create it. The best part? It automatically handles spaces, special characters, and proper encoding. You don’t need to worry about any of that.

Step 3: Get the Final URL

Once you’ve added all your parameters, you can get the complete URL as a string using the toString() method.

console.log(url.toString());
// Output: https://example.com/search?q=web+dev&page=2

Notice how the spaces in "web dev" have been automatically converted to + signs? The URL object did that for you. If there were special characters like & or ?, it would have encoded those properly too.

Code Example 1: Building a Complete Search URL

Let’s put it all together in a practical example. Imagine you’re building a search feature for a recipe website. You need to create a URL that includes the search term, a category filter, and a results limit.

// Create the base URL for our recipe search page
const recipeUrl = new URL('https://cookingexample.com/recipes');

// Add search parameters
recipeUrl.searchParams.set('query', 'chocolate cake');
recipeUrl.searchParams.set('category', 'desserts');
recipeUrl.searchParams.set('maxResults', '10');

// Add another parameter conditionally
const vegetarianOnly = true;
if (vegetarianOnly) {
  recipeUrl.searchParams.set('vegetarian', 'true');
}

// Get the final URL
const finalUrl = recipeUrl.toString();
console.log(finalUrl);

What this code does:

  1. We start with a base URL for a recipe search page.
  2. We add three parameters: what to search for (query), which category to filter (category), and how many results to show (maxResults).
  3. We demonstrate how to add a parameter conditionally. The if statement checks if vegetarianOnly is true, and if so, adds a vegetarian parameter.
  4. Finally, we convert the URL object to a string and log it.

The output will be:

https://cookingexample.com/recipes?query=chocolate+cake&category=desserts&maxResults=10&vegetarian=true

All the spaces and special characters are properly encoded, and the parameters are correctly separated by & symbols. You didn’t have to manage any of that manually.

Reading Parameters from the Current URL

Building URLs is only half the battle. You also need to read parameters from the URL when someone visits your page. For example, if a user clicks a link with parameters, your JavaScript needs to extract those values and use them.

Step 1: Get the Query String

The query string is everything after the ? in a URL. In a browser, you can access it through window.location.search.

// In a browser environment
const queryString = window.location.search;
console.log(queryString); // Output: ?q=web+dev&page=2

If you’re working with a URL string directly (not the current page), you can extract the query string manually or just pass the full URL to URLSearchParams.

Step 2: Create a URLSearchParams Object

Once you have the query string, create a URLSearchParams object to parse it.

const params = new URLSearchParams(queryString);

This object now contains all your parameters, ready to be accessed.

Step 3: Extract Parameter Values

Use the get() method to retrieve values by their parameter name.

const searchQuery = params.get('q');
const pageNumber = params.get('page');

console.log(`Searching for: ${searchQuery}`);
console.log(`Page number: ${pageNumber}`);

If a parameter doesn’t exist, get() returns null. This is important to remember when writing your code—you should always check if a value exists before using it.

Code Example 2: Reading Parameters on Page Load

Here’s a complete example that reads parameters when a webpage loads and uses them to display a personalized message.

// This code runs when the page loads
window.addEventListener('DOMContentLoaded', () => {
  // Get the query string from the current URL
  const params = new URLSearchParams(window.location.search);
  
  // Extract the 'name' parameter
  const userName = params.get('name');
  
  // Extract the 'theme' parameter
  const theme = params.get('theme');
  
  // Check if the name parameter exists and display it
  const greetingElement = document.getElementById('greeting');
  if (userName) {
    greetingElement.textContent = `Welcome, ${userName}!`;
  } else {
    greetingElement.textContent = 'Welcome, Guest!';
  }
  
  // Apply a theme if specified
  if (theme === 'dark') {
    document.body.style.backgroundColor = '#333';
    document.body.style.color = '#fff';
  }
  
  // Log all parameters for debugging
  console.log('All parameters:');
  for (const [key, value] of params) {
    console.log(`${key}: ${value}`);
  }
});

What this code does:

  1. We wait for the page to load using DOMContentLoaded to ensure all HTML is ready.
  2. We create a URLSearchParams object from the current page’s query string.
  3. We try to get the name parameter. If it exists, we display a personalized greeting. If not, we show a default message.
  4. We check if the theme parameter is set to 'dark'. If so, we change the page’s colors.
  5. We loop through all parameters using a for...of loop and log them. This is great for debugging.

If you visited a page with the URL https://yoursite.com/welcome?name=Alex&theme=dark, this script would display “Welcome, Alex!” and switch to a dark theme.

Common Mistakes to Avoid

Even with these helpful tools, beginners often run into the same issues. Here are the most common mistakes and how to avoid them:

1. Forgetting to Check for Null Values

The get() method returns null if a parameter doesn’t exist. If you try to use this value without checking, you might get unexpected results.

// Mistake
const params = new URLSearchParams(window.location.search);
const username = params.get('user');
console.log(username.toUpperCase()); // Error if 'user' doesn't exist!

// Solution
const username = params.get('user');
if (username) {
  console.log(username.toUpperCase());
} else {
  console.log('No username provided');
}

Always check if a parameter exists before using it.

2. Modifying the URL String Directly

Some learners fetch the full URL, try to edit it as a plain string, and then put it back together. This is exactly what we’re trying to avoid.

// Don't do this!
const url = window.location.href;
const newUrl = url + '?page=2'; // Breaks if URL already has parameters
window.location.href = newUrl;

Instead, always use the URL object to modify URLs.

3. Confusing Parameter Names

Parameter names are case-sensitive. ?page=2 is different from ?Page=2. Make sure you use consistent naming.

const params = new URLSearchParams('?Page=2');
console.log(params.get('page')); // null
console.log(params.get('Page')); // '2'

Choose a naming convention (like lowercase) and stick to it throughout your project.

4. Not Encoding Special Characters

While URLSearchParams handles encoding automatically, some beginners still try to manually encode values before passing them, leading to double-encoding.

// Mistake
const term = encodeURIComponent('hello world');
url.searchParams.set('q', term); // Results in double-encoded value

// Just do this
url.searchParams.set('q', 'hello world'); // Automatic encoding

Trust the built-in methods to handle encoding for you.

Troubleshooting: When Things Go Wrong

Even with the right approach, you might encounter issues. Here are some actionable tips to get you back on track.

Problem: Nothing Happens When I Run My Code

Solution: Open your browser’s Developer Tools and check the Console for errors. Press F12 or Ctrl+Shift+I (Windows/Linux) or Cmd+Option+I (Mac) to open DevTools. Look for red error messages—they’ll tell you exactly what went wrong.

Add console.log() statements at key points in your code to confirm it’s running:

console.log('Script started');
const params = new URLSearchParams(window.location.search);
console.log('Query string:', window.location.search);
console.log('Params object:', params);

This helps you see where the code might be failing.

Problem: My Parameters Aren’t Showing Up in the URL

Solution: Make sure you’re actually using the final URL string. Creating a URL object and setting parameters doesn’t automatically change the browser’s address. You need to assign the result to something or navigate to it.

const url = new URL(window.location.href);
url.searchParams.set('test', 'value');

// This changes the page URL
window.location.href = url.toString();

// Or if you're building a link:
const link = document.createElement('a');
link.href = url.toString();

Problem: I’m Getting “URL is not defined” Errors

Solution: You’re likely running your code outside of a browser environment (like Node.js) without the proper setup. The URL and URLSearchParams objects are built into modern browsers. If you’re using Node.js, make sure you’re using a version that supports these (Node 10+). For older environments, you might need a polyfill, but as a beginner, focus on modern browsers first.

Problem: Selectors Don’t Match My HTML

Solution: If you’re trying to update page content based on URL parameters but nothing appears, double-check that your JavaScript selectors match your HTML elements exactly.

// HTML: <div id="greeting"></div>
// JavaScript:
const element = document.getElementById('greeting'); // Correct
// const element = document.getElementById('Greeting'); // Wrong (case-sensitive)
// const element = document.querySelector('.greeting'); // Wrong (looks for class, not ID)

Use console.log(element) to verify you’ve actually selected the element. If it logs null, your selector is wrong.

Problem: Parameters Disappear After Page Reload

Solution: This usually happens when you’re not preserving the parameters during navigation. If you have links on your page, make sure they include the current parameters.

// When creating new links, copy current parameters
const currentParams = new URLSearchParams(window.location.search);
const newUrl = new URL('/other-page', window.location.origin);
for (const [key, value] of currentParams) {
  newUrl.searchParams.set(key, value);
}

This copies all existing parameters to the new URL before navigating.

Practice Exercises

The best way to learn is by doing. Try these exercises to solidify your understanding:

Exercise 1: Build a Simple Search Form

Create an HTML page with a search box and a button. When the user clicks the button, build a URL with their search term and navigate to it.

<!DOCTYPE html>
<html>
<head>
  <title>Search Demo</title>
</head>
<body>
  <input type="text" id="searchBox" placeholder="Enter search term">
  <button id="searchButton">Search</button>

  <script>
    document.getElementById('searchButton').addEventListener('click', () => {
      const searchTerm = document.getElementById('searchBox').value;
      const url = new URL('https://example.com/search');
      url.searchParams.set('q', searchTerm);
      window.location.href = url.toString();
    });
  </script>
</body>
</html>

Exercise 2: Create a Parameter Reader Page

Build a page that reads multiple parameters and displays them in a list. Include error handling for missing parameters.

<!DOCTYPE html>
<html>
<head>
  <title>Parameter Reader</title>
</head>
<body>
  <h1>URL Parameters</h1>
  <ul id="paramList"></ul>

  <script>
    const params = new URLSearchParams(window.location.search);
    const listElement = document.getElementById('paramList');
    
    if ([...params].length === 0) {
      listElement.innerHTML = '<li>No parameters found</li>';
    } else {
      for (const [key, value] of params) {
        const li = document.createElement('li');
        li.textContent = `${key}: ${value}`;
        listElement.appendChild(li);
      }
    }
  </script>
</body>
</html>

Exercise 3: Wrap Logic in Reusable Functions

Create two functions: buildUrl(base, params) and getParam(name). Use them throughout a small project.

function buildUrl(baseUrl, paramObject) {
  const url = new URL(baseUrl);
  for (const [key, value] of Object.entries(paramObject)) {
    url.searchParams.set(key, value);
  }
  return url.toString();
}

function getParam(paramName) {
  const params = new URLSearchParams(window.location.search);
  return params.get(paramName);
}

// Usage:
const myUrl = buildUrl('https://example.com/page', {
  id: '123',
  sort: 'newest'
});
console.log(myUrl); // https://example.com/page?id=123&sort=newest

const pageId = getParam('id');
console.log(pageId); // '123' (or null if not present)

Next Steps: Building Real Projects

Now that you understand the basics, it’s time to apply this knowledge to real-world scenarios. Here are some ideas to take your skills further:

Idea 1: Build a Simple Blog Filter

Create a blog page where readers can filter posts by category and date range using URL parameters. When they select filters, update the URL. When the page loads, read those filters and show only matching posts. This teaches you how to maintain state through page reloads.

Idea 2: Create a Shareable Wishlist

Build a product page where users can click items to add them to a wishlist. Store the selected item IDs in URL parameters so users can share their wishlist with others via a link. This demonstrates how URL parameters can store application state.

Idea 3: Develop a Multi-Step Form

Create a form that spans multiple pages. Use URL parameters to pass data from one step to the next. This helps you understand how to maintain data across page navigations without server-side storage.

Idea 4: Learn About URL Hash Parameters

Once you’re comfortable with search parameters (?key=value), explore hash parameters (#section). They’re useful for single-page applications and don’t trigger page reloads. The URL object can access these via url.hash.

Idea 5: Organize Your Code into Modules

As your projects grow, you’ll want to organize your URL-handling functions into separate modules. Create a url-utils.js file that exports your buildUrl and getParam functions. Then import them where needed:

// url-utils.js
export function buildUrl(baseUrl, params) { /* ... */ }
export function getParam(name) { /* ... */ }

// main.js
import { buildUrl, getParam } from './url-utils.js';

This keeps your code clean and reusable across projects.

Summary

Passing parameters in a URL is a fundamental web development skill, and JavaScript’s URL and URLSearchParams objects make it incredibly simple. Instead of wrestling with string concatenation and manual encoding, you can use these built-in tools to build robust, error-free URLs in just a few lines of code.

Key takeaways:

Remember to open your browser’s Developer Tools when testing, add plenty of console.log() statements to understand what’s happening, and always verify that your HTML selectors match your JavaScript code. With these practices, you’ll be building dynamic, parameter-driven web pages in no time.

Start small, practice with the exercises provided, and soon you’ll be ready to tackle larger projects that use URL parameters to create rich, interactive experiences for your users. Happy coding!