Redirect to URL With Parameters in JavaScript

This tutorial will teach you how to redirect the user to a new URL while preserving and/or adding URL parameters.

Published Categorized as JavaScript

Imagine you want to send the user to a different URL, along with extra URL parameters, using JavaScript. You might be wondering about the best way to achieve this.

Redirect And Pass New Parameters to the Destination

To make this happen, you can create a JavaScript function that takes two inputs: the URL you want to direct the user to and the URL parameters you want to include.

To give your function flexibility, it’s a good idea to allow any number of URL parameters to be passed to the function as key/value pairs. This way, you can accommodate varying parameter requirements for each function call.

Here’s what your function could look like:

function redirectTo(destination, params) {
  // Build the query string from the parameters
  var queryString = Object.keys(params)
    .map(function (key) {
      return encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
    })
    .join("&");

  // Append the query string to the redirect URL
  destination += "?" + queryString;

  // Redirect the user to the new URL
  window.location.href = destination;
}

And here’s an example way to call the function:

redirectTo(window.location.href, { testKey: 'testValue', anotherTestKey: 'anotherTestValue' });

In the example, we are using the window.location.href property to get the current URL of the browser window, then passing on two URL parameters to it:

  • testKey=testValue
  • anotherTestkey=anotherTestValue

Redirect, Pass New Parameters, And Preserve Old Ones

Now imagine you needed to preserve the existing URL parameters of the page and, optionally, pass on new URL parameters to the destination.

You can achieve this by rewriting the function to something like this:

function redirectTo(destination, params) {
  // Get the current URL's query string
  var currentParams = window.location.search.slice(1);

  // Merge the current parameters with the new parameters
  var mergedParams = Object.assign({}, parseQueryString(currentParams), params);

  // Build the query string from the merged parameters
  var queryString = Object.keys(mergedParams)
    .map(function (key) {
      return encodeURIComponent(key) + "=" + encodeURIComponent(mergedParams[key]);
    })
    .join("&");

  // Append the query string to the redirect URL
  destination += "?" + queryString;

  // Redirect the user to the new URL
  window.location.href = destination;
}

// Helper function to parse a query string into an object
function parseQueryString(queryString) {
  var params = {};
  if (queryString) {
    queryString.split("&").forEach(function (pair) {
      var parts = pair.split("=");
      var key = decodeURIComponent(parts[0]);
      var value = decodeURIComponent(parts[1] || "");
      params[key] = value;
    });
  }
  return params;
}

The function parses the existing URL parameters, merges them with the new URL parameters you’ve passed onto the function at calling, then constructs a final URL to redirect the user to using the destination URL and the URL parameters.

Redirect, Pass Only Existing Parameters

Of course, if you only needed to redirect the user to a new URL and pass on any existing parameters to it, you could simplify the function to something like this:

function redirectTo(destination) {
  // Get the current URL's query string
  var currentParams = window.location.search;

  // Append the current query string to the destination URL
  destination += currentParams;

  // Redirect the user to the new URL
  window.location.href = destination;
}

In such a case, calling the function would be as simple as:

var destinationUrl = "https://example.com/";
redirectTo(destinationUrl);

Bottom Line

Thanks for reading this far!

I hope this tutorial helped you figure out how to develop a JavaScript redirect to a destination URL with URL parameters.

We’ve gone over ways to preserve the existing parameters, pass on new parameters, as well as merge the existing parameters while passing on new ones to the destination.

By Dim Nikov

Editor of Maker's Aid. Part programmer, part marketer. Making things on the web and helping others do the same since the 2000s. Yes, I had Friendster and Myspace.

Leave a comment

Your email address will not be published. Required fields are marked *