This version will update its internal cache of parameters each time the history changes. 1 Jan-2022: if you need all values of the same parameter name as an array then use searchParams.getAll(prop). – andy Apr 6 at 19:47 EDIT: You can use URL interface, its quite widely adopted in almost all the new browser and if the code is going to run on an old browser you can use a polyfill like this one. Here's a code example on how to use URL interface to get query parameters (aka search parameters)
import React, { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
function CheckoutDetails() {
const location = useLocation();
const [amountValue, setAmountValue] = useState(1);
// function to get query params using URLSearchParams
useEffect(() => {
const searchParams = new URLSearchParams(location.search);
if (searchParams.has("amount")) {
const amount = searchParams.get("amount");
setAmountValue(parseInt(amount, 10));
} else {
setAmountValue(1);
}
}, [location]);
return (
<p>Amount: {amountValue}</p>
)
Update: Jan-2022
Using Proxy()
is faster than using Object.fromEntries()
and better supported
const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
// Get the value of "some_key" in eg "https://example.com/?some_key=some_value"
let value = params.some_key; // "some_value"
Update: June-2021
For a specific case when you need all query params:
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
Original
You don't need jQuery for that purpose. You can use just some pure JavaScript:
function getParameterByName(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
Usage:
// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)
The URLSearchParams provides an interface to work with query string parameters The URLSearchParams is an iterable so you can use the for...of construct to iterate over query string parameters. To work with the query string, you can use the URLSearchParams object. The URLSearchParams is an iterable object, therefore you can use the for...of structure to iterate over its elements which are query string parameters:
Summary: in this tutorial, you will learn how to use the URLSearchParams
to get query string parameters in JavaScript.
To get a query string you can access the search
property of the object:
.wp - block - code {
border: 0;
padding: 0;
}
.wp - block - code > div {
overflow: auto;
}
.shcb - language {
border: 0;
clip: rect(1 px, 1 px, 1 px, 1 px); -
webkit - clip - path: inset(50 % );
clip - path: inset(50 % );
height: 1 px;
margin: -1 px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1 px;
word - wrap: normal;
word - break: normal;
}
.hljs {
box - sizing: border - box;
}
.hljs.shcb - code - table {
display: table;
width: 100 % ;
}
.hljs.shcb - code - table > .shcb - loc {
color: inherit;
display: table - row;
width: 100 % ;
}
.hljs.shcb - code - table.shcb - loc > span {
display: table - cell;
}
.wp - block - code code.hljs: not(.shcb - wrap - lines) {
white - space: pre;
}
.wp - block - code code.hljs.shcb - wrap - lines {
white - space: pre - wrap;
}
.hljs.shcb - line - numbers {
border - spacing: 0;
counter - reset: line;
}
.hljs.shcb - line - numbers > .shcb - loc {
counter - increment: line;
}
.hljs.shcb - line - numbers.shcb - loc > span {
padding - left: 0.75 em;
}
.hljs.shcb - line - numbers.shcb - loc::before {
border - right: 1 px solid #ddd;
content: counter(line);
display: table - cell;
padding: 0 0.75 em;
text - align: right; -
webkit - user - select: none; -
moz - user - select: none; -
ms - user - select: none;
user - select: none;
white - space: nowrap;
width: 1 % ;
}
location.search
Code language: CSS(css)
Assuming that the value of the location.search
is:
'?type=list&page=20'
Code language: JavaScript(javascript)
const urlParams = new URLSearchParams(location.search);
Code language: JavaScript(javascript)
Output:
type: list
page: 20
Code language: CSS(css)
The following example uses the keys()
method to list all parameter names of a query string:
const urlParams = new URLSearchParams('?type=list&page=20');
for (const key of urlParams.keys()) {
console.log(key);
}
Code language: JavaScript(javascript)
To parse the query parameters into an object, use URL.searchParams's .entries() method, which returns an Iterator of key/value pairs, and Object.fromEntries to convert it into an object. url.searchParams is the same type of instance object returned by URLSearchParams. The URLSearchParams interface is supported by all major browser versions except IE 11. It works by parsing the query string of a URL and providing a way to access the values. For example: We can then use this plain JS function to parse a single query param into a string:
let params = new URLSearchParams('q=node&page=2');
params.get('q'); // 'node'
params.get('page'); // '2'
One of the downsides of this interface is that you must pass it only the query string of a URL. If you're working with the current browser URL, that's easy to do since you can just pass window.location.search
. If you're working with any other URL, you'll need to parse out and pass the query string separately.
let params = new URLSearchParams('q=node&page=2');
let entries = params.entries();
Object.fromEntries(entries); // {q: 'node', page: '2'}
The URL
API is also supported by all major browser versions except IE 11. It offers a more flexible way to parse URLs, and it also provides a way to access the query string values. For example:
const url = new URL('https://stackabuse.com/search?q=node&page=2');
const searchParams = url.searchParams;
searchParams.get('q'); // 'node'
searchParams.get('page'); // '2'
If for any reason you're not able to access the APIs above or want to have more control over the parsing, you can use the following code to parse the query string into an object.
function getQueryParams(url) {
const paramArr = url.slice(url.indexOf('?') + 1).split('&');
const params = {};
paramArr.map(param => {
const [key, val] = param.split('=');
params[key] = decodeURIComponent(val);
})
return params;
}
Note: There are many ways to parse query params in plain JS, some more complicated (and robust) than others. This is just one way, and was adapted from this gist.
We can then use this plain JS function to parse a single query param into a string:
getQueryParams('https://stackabuse.com/search?q=node&page=2')
// { q: 'node', page: '2' }
Note: don’t pass the full URL as a parameter to URLSearchParams(), but only the query string part of the URL, which you access using window.location.search. The parameters passed as a query string are normally used server-side, to generate a proper response. Here’s how you can access query parameters using Node.js. To access the value of the query inside the browser, using JavaScript, we have a special API called URLSearchParam, supported by all modern browsers We also have sort() to sort parameters by key value, and we have the toString() method to generate a query string from the values.
The HTTP protocol allows the request to a web page to be made with a query string.
Like this:
https: //test.com/?name=roger
https: //test.com/hello?name=roger
In this case we have a single query parameter, named name
, with the value roger
.
You can have multiple parameters, like this:
https: //test.com/hello?name=roger&age=20
const params = new URLSearchParams(window.location.search)
params.has('test')
params.get('test')
You must use the “useLocation” hook to get parameter value from the query string with React Router. Here is how to do it! Also, check out the guidelines you should follow for best use of React hooks. Here are the three methods to follow to get parameter values from the query string. 2. To obtain parameter value from query string with React Router Ways to get parameter value from the query string
import React from "react";
import {
useLocation
} from "react-router-dom";
const MyComponent = () => {
const {
language
} = useLocation();
const name = new URLSearchParams(language).get("name");
console.log(name);
};
import React from "react";
import {
useLocation
} from "react-router-dom";
constMyComponent = () => {
const {
search
} = useLocation();
const id = new URLSearchParams(search).get("id");
console.log(id);
};
Open your terminal and then execute the following common on the terminal to create the new react app.
npx create - react - app my - react - app
To add the query string and bootstrap 4 libraries to your react project, run the command listed below next.
npm install bootstrap--save
npm install query - string
After that, you must add the react-router and boostrap.min.css file in the src/App.js file.
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import {
BrowserRouter as Router,
Switch,
Route
} from 'react-router-dom';
function App() {
return (
);
}
export default App;
To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1. This is the default but you can change the script name in the Parameters window to something more descriptive such as orderDateParam or productParam, and then use this in the query string. This is an alternative to creating a short link to use that serializes the parameter values. Passing parameters through the URL can be simpler, and there is the benefit of the parameter values being more human-readable.
When embedding a Dundas BI view, there is a base URL that you need to construct that consists of the Dundas BI server address, the file type that you want to embed, its ID, and the view options (passed via the query string).
For example, a base URL for embedding a dashboard might be:
https: //dbi.example.com/Dashboard/092741e1-61a4-4ee8-925a-1e78a90260ad?e=false&vo=viewOnly
For example, if your dashboard has a Single Date filter (and associated view parameter) on an implicit date-time hierarchy, the following URL can be used to view the dashboard with the filter set to a specific date (Jan 31, 2006):
https: //dbi.example.com/Dashboard/092741e1-61a4-4ee8-925a-1e78a90260ad?e=false&vo=viewOnly&$viewParameter1=2006-01-31
has(): This is to check if the query string contains a specific parameter. get(): This is to get the value of a specific parameter. getAll(): This is to get an array of all the values in the query string. values(): This is to iterate over the values of the query string.
https: //example.com?name=Shubham&age=22
// let's assume current URL is: https://example.com?name=Shubham&age=22
window.location.search
// here the window.location.search will be:
// ?name=Shubham&age=22
const queryParams = new URLSearchParams(window.location.search)
This is one of the easiest ways to get query string values in JavaScript. The URLSearchParams interface provides utility methods to work with the query string of a URL. You can check browser support with Can I use. Today, we discussed the different methods that you can use to get the query string in JavaScript. Along with the vanilla JavaScript, we also discussed how you can use the URLSearchParams interface to get query string variables. In this post, we’ll discuss how you can build a custom function to get query string parameters in vanilla JavaScript. Later on, we’ll also explore the URLSearchParams interface to understand how it works and how it can help with query string parameters.
In this section, we’ll see how you can get query string values with vanilla JavaScript.
Let’s go through the following JavaScript example.
function getQueryStringValues(key) {
var arrParamValues = [];
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var arrParamInfo = url[i].split('=');
if (arrParamInfo[0] == key || arrParamInfo[0] == key + '[]') {
arrParamValues.push(decodeURIComponent(urlparam[1]));
}
}
return (arrParamValues.length > 0 ? (arrParamValues.length == 1 ? arrParamValues[0] : arrParamValues) : null);
}
// index.php?keyword=FooBar&hobbies[]=sports&hobbies[]=Reading
console.log(getQueryStringValues('keyword')); // "FooBar"
console.log(getQueryStringValues('hobbies')); // Array [ "sports", "Reading" ]
console.log(getQueryStringValues('keyNotExits')); // null
Let’s go through the function to see how it works.
The following snippet is one of the most important snippets in the function.
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
Firstly, we’ve used the indexOf
method to find the position of the ?
character in the URL. Next, we’ve used the slice
method to extract the query string part in the URL. Finally, we’ve used the split
method to split the query string by the &
character. Thus, the url
variable is initialized with an array of query string parameters.
Next, we loop through all the elements of the url
array. In the loop, we use the split
method to split the array value by the =
character. And with that, the arrParamInfo
variable is initialized with an array, where the array key is the parameter name and the array value is the parameter value. You can see that in the following snippet.
var arrParamInfo = url[i].split('=');
Finally, if the arrParamValues
variable contains values, we’ll return it, otherwise null
is returned.
return (arrParamValues.length > 0 ? (arrParamValues.length == 1 ? arrParamValues[0] : arrParamValues) : null);
Let’s quickly see how it works.
// index.php?keyword=Search Text&click=Submit
var urlParams = new URLSearchParams(window.location.search);
URL parameters (also called query string parameters or URL variables) are used to send small amounts of data from page to page, or from client to server via a URL. They can contain all kinds of useful information, such as search queries, link referrals, product information, user preferences, and more. URLSearchParams also provides some familiar Object iterator methods, allowing you iterate over its keys, values and entries: You can use URLSearchParams.getAll() to return all of the values associated with a particular parameter: We can then parse the query string’s parameters using URLSearchParams:
In modern browsers, this has become a lot easier, thanks to the URLSearchParams interface. This defines a host of utility methods to work with the query string of a URL.
Assuming that our URL is https://example.com/?product=shirt&color=blue&newuser&size=m
, we can grab the query string using window.location.search
:
const queryString = window.location.search;
console.log(queryString);
// ?product=shirt&color=blue&newuser&size=m
We can then parse the query string’s parameters using URLSearchParams
:
const urlParams = new URLSearchParams(queryString);
Then we call any of its methods on the result.
For example, URLSearchParams.get()
will return the first value associated with the given search parameter:
const product = urlParams.get('product')
console.log(product);
// shirt
const color = urlParams.get('color')
console.log(color);
// blue
const newUser = urlParams.get('newuser')
console.log(newUser);
// empty string
console.log(urlParams.getAll('size'));
// [ 'm' ]
//Programmatically add a second size parameter.
urlParams.append('size', 'xl');
console.log(urlParams.getAll('size'));
// [ 'm', 'xl' ]
const
keys = urlParams.keys(),
values = urlParams.values(),
entries = urlParams.entries();
for (const key of keys) console.log(key);
// product, color, newuser, size
for (const value of values) console.log(value);
// shirt, blue, , m
for (const entry of entries) {
console.log(`${entry[0]}: ${entry[1]}`);
}
// product: shirt
// color: blue
// newuser:
// size: m