How to add or update query string parameters to given URL?
I wrote the following function which used in order to accomplish the required functionality :
/// <summary>
/// Get URL With QueryString Dynamically
/// </summary>
/// <param name="url">URI With/Without QueryString</param>
/// <param name="newQueryStringArr">New QueryString To Append</param>
/// <returns>Return Url + Existing QueryString + New/Modified QueryString</returns>
public string BuildQueryStringUrl(string url, string[] newQueryStringArr)
{
string plainUrl;
var queryString = string.Empty;
var newQueryString = string.Join("&", newQueryStringArr);
if (url.Contains("?"))
{
var index = url.IndexOf('?');
plainUrl = url.Substring(0, index); //URL With No QueryString
queryString = url.Substring(index + 1);
}
else
{
plainUrl = url;
}
var nvc = HttpUtility.ParseQueryString(queryString);
var qscoll = HttpUtility.ParseQueryString(newQueryString);
var queryData = string.Join("&",
nvc.AllKeys.Where(key => !qscoll.AllKeys.Any(newKey => newKey.Contains(key))).
Select(key => string.Format("{0}={1}",
HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key]))).ToArray());
//Fetch Existing QueryString Except New QueryString
var delimiter = nvc.HasKeys() && !string.IsNullOrEmpty(queryData) ? "&" : string.Empty;
var queryStringToAppend = "?" + newQueryString + delimiter + queryData;
return plainUrl + queryStringToAppend;
}
Function Usage -
Suppose given url is - http://example.com/Test.aspx?foo=bar&id=100
And you want to change foo value to chart and also you want to add new query string say hello = world and testStatus = true then -
Input to Method Call :
BuildQueryStringUrl("http://example.com/Test.aspx?foo=bar&id=100",
new[] {"foo=chart", "hello=world", "testStatus=true"});
Output : http://example.com/Test.aspx?foo=chart&hello=world&testStatus=true&id=100
Hope this helps.
Adding a parameter to the URL with JavaScript
A basic implementation which you'll need to adapt would look something like this:
function insertParam(key, value) {
key = encodeURIComponent(key);
value = encodeURIComponent(value);
// kvp looks like ['key1=value1', 'key2=value2', ...]
var kvp = document.location.search.substr(1).split('&');
let i=0;
for(; i<kvp.length; i++){
if (kvp[i].startsWith(key + '=')) {
let pair = kvp[i].split('=');
pair[1] = value;
kvp[i] = pair.join('=');
break;
}
}
if(i >= kvp.length){
kvp[kvp.length] = [key,value].join('=');
}
// can return this or...
let params = kvp.join('&');
// reload page with new params
document.location.search = params;
}
This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match
the slow regex method I benchmarked against for completions sake (approx +150% slower)
function insertParam2(key,value)
{
key = encodeURIComponent(key); value = encodeURIComponent(value);
var s = document.location.search;
var kvp = key+"="+value;
var r = new RegExp("(&|\\?)"+key+"=[^\&]*");
s = s.replace(r,"$1"+kvp);
if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;};
//again, do what you will here
document.location.search = s;
}
How to add or replace a query parameter in a URL using Javascript/jQuery?
You could use a jQuery plugin to do the all the heavy lifting for you. It will parse the query string, and also reconstruct the updated query string for you. Much less code to deal with.
Plugin Download Page
Github Repo
// URL: ?a=2&b=3&order_by=old_data
var order_by = $.query.get('order_by');
//=> old_data
// Conditionally modify parameter value
if (order_by) {
order_by = “data”;
}
// Inject modified parameter back into query string
var newUrl = $.query.set(“order_by”, order_by).toString();
//=> ?a=2&b=3&order_by=data
For those using Node.js, there is a package for this available in NPM.
NPM Package
Github Repo
var queryString = require('query-string');
var parsed = queryString.parse('?a=2&b=3&order_by=old_data'); // location.search
// Conditionally modify parameter value
if (parsed.order_by) {
parsed.order_by = 'data';
}
// Inject modified parameter back into query string
const newQueryString = queryString.stringify(parsed);
//=> a=2&b=3&order_by=data
Add or update query string parameter - URL remains unchanged
This function is not changing the url. It's simply returning a string.
If you wanna change the url (reloading the page) you should write something like this:
window.location.href = UpdateQueryString(your_key, your_value, your_url)
If you wanna change the url without reloading the entire page, using the HTML5 History/State APIs, you might be interested in this:
https://github.com/browserstate/history.js/
How do you programmatically update query params in react-router?
Within the push
method of hashHistory
, you can specify your query parameters. For instance,
history.push({
pathname: '/dresses',
search: '?color=blue'
})
or
history.push('/dresses?color=blue')
You can check out this repository for additional examples on using history
Change URL parameters and specify defaults using JavaScript
To answer my own question 4 years later, after having learned a lot. Especially that you shouldn't use jQuery for everything. I've created a simple module that can parse/stringify a query string. This makes it easy to modify the query string.
You can use query-string as follows:
// parse the query string into an object
var q = queryString.parse(location.search);
// set the `row` property
q.rows = 10;
// convert the object to a query string
// and overwrite the existing query string
location.search = queryString.stringify(q);
Updating existing URL querystring values with jQuery
Get query string values this way and use $.param to rebuild query string
UPDATE:
This is an example, also check fiddle:
function getQueryVariable(url, variable) { var query = url.substring(1); var vars = query.split('&'); for (var i=0; i<vars.length; i++) { var pair = vars[i].split('='); if (pair[0] == variable) { return pair[1]; } }
return false; }
var url = 'http://www.example.com/hello.png?w=100&h=100&bg=white'; var w = getQueryVariable(url, 'w'); var h = getQueryVariable(url, 'h'); var bg = getQueryVariable(url, 'bg');
// http://www.example.com/hello.png?w=200&h=200&bg=white var params = { 'w':200, 'h':200, 'bg':bg }; var new_url = 'http://www.example.com/hello.png?' + jQuery.param(params);
Related Topics
Jquery: Simplest Way to Check Url for a Parameter and Pass It to Anchor Href If It Exists
Vuejs Reload If in the Same Route
Change Button Color When Click on the Button
Prevent React-Router History.Push from Reloading Current Route
Display Images in React Using Jsx Without Import
Check If a String Has White Space
What's the Best Way to Reload/Refresh an Iframe
Dynamically Change Background Color on Scroll
Why React Props Are Passed Undefined to the Child Component
How to Delete Rows of Data Using Sequelize
How to Remove Single Uploaded File from Jquery in Multiple File Upload
Way to Access Const from Another Component in React
How to Read a CSV File into a 2D Array in JavaScript
Javascript or Jquery Browser Back Button Click Detector
Hide Div If Value Is Blank (Javascript)
Uncaught Typeerror: Cannot Read Property 'Click' of Null Chrome Extension