Read a QueryString value in the browser (JavaScript and jQuery)
Scripts often need a value from the page URL: orders.aspx?status=open&page=2. ASP.NET reads it with Request.QueryString on the server; in the browser, the standard URLSearchParams object does the same job, decoding included. jQuery has no helper for it and does not need one.
URLSearchParams
// URL: /orders.aspx?status=open&page=2&tag=a&tag=b&q=caf%C3%A9+cr%C3%A8me
var params = new URLSearchParams(window.location.search);
params.get("status"); // "open"
params.get("page"); // "2" (always a string)
params.get("missing"); // null
params.has("status"); // true
params.getAll("tag"); // ["a", "b"]
params.get("q"); // "café crème" (+ and %XX are decoded)
var page = parseInt(params.get("page"), 10) || 1;
Values are strings; convert them and supply defaults. getAll handles repeated keys, which get reduces to the first value.
Using it with jQuery
$(function () {
var status = new URLSearchParams(location.search).get("status") || "all";
$("#statusFilter").val(status);
$(".tab[data-status='" + CSS.escape(status) + "']").addClass("active");
});
CSS.escape protects the selector against characters such as quotes in the value. Never write a query string value into the page with .html(): use .text() or .val(), or you create a cross-site scripting hole.
Older code: the regular-expression helper
Before URLSearchParams (supported by all current browsers, not by Internet Explorer), tutorials used a function like this. You will meet it in existing projects:
function getQueryValue(name) {
var escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
var m = new RegExp("[?&]" + escaped + "=([^&#]*)").exec(location.search);
return m ? decodeURIComponent(m[1].replace(/\+/g, " ")) : null;
}
Note the + replacement: in query strings produced by forms, a space is encoded as +, which decodeURIComponent alone does not convert.
Building a URL with parameters
var p = new URLSearchParams({ status: "open", page: 3 });
location.href = "orders.aspx?" + p.toString(); // status=open&page=3, encoded
The server decides
Anything a script reads from the URL, the server reads too, and the user can edit both. Use client-side values for display only, and validate them in the code-behind as shown in Passing multiple QueryString parameters. Values after # are a different part of the URL: see Read the URL hash.
Updating the URL without reloading
When a filter changes on the page, you can keep the URL in sync so that refreshing or sharing it restores the same view:
var params = new URLSearchParams(location.search);
params.set("status", "closed");
params.delete("page");
history.replaceState(null, "", location.pathname + "?" + params.toString());
replaceState changes the address bar without a new request or history entry; use pushState if the back button should return to the previous filter.
Official documentation
- MDN: URLSearchParams, Location.search, CSS.escape()
- jQuery API: .text()