Skip to content

Instantly share code, notes, and snippets.

@joshcutler
Created November 13, 2009 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshcutler/233979 to your computer and use it in GitHub Desktop.
Save joshcutler/233979 to your computer and use it in GitHub Desktop.
Javascript snippet for taking a url and updating query string paramters
function add_or_update_query_param(name, value, starter_url)
{
url = starter_url || window.location.href;
query_string_chunks = url.split("?");
base_url = query_string_chunks[0];
query_string = (query_string_chunks.length == 2) ? query_string_chunks[1] : null;
chunks = [];
new_value_updated = false;
if (query_string)
{
name_value_pairs = query_string.split("&")
for (var i = 0; i < name_value_pairs.length; i++)
{
pair = name_value_pairs[i].split("=");
if (pair.length == 2)
{
if (pair[0].toLowerCase() === name.toLowerCase())
{
chunks.push(name + "=" + value);
new_value_updated = true;
}
else
{
chunks.push(pair[0] + "=" + pair[1]);
}
}
}
}
if (!new_value_updated)
{
chunks.push(name + "=" + value);
}
return (base_url + "?" + chunks.join("&"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment