- How to get URL parameters in javascript
- Share if it’s worth .
- How to Get «Get» Request Parameters in JavaScript
- How can I get query string values in JavaScript?
- How to get URL parameter using jQuery or plain JavaScript?
- Get the values from the GET parameters (JavaScript)
- How to retrieve GET parameters from JavaScript
- How to pass parameters in GET requests with jQuery
- How to retrieve query parameters from GET request using javascript?
- Getting the url parameters inside the html page
How to get URL parameters in javascript
Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home3/codippac/public_html/wp-content/plugins/wp-syntax/wp-syntax.php on line 380
A URL consists of a root and some parameters that carry some data. These parameters are in the key-value pairs and separated by ‘&’ character. Also, the list of parameters and the actual URL are separated by a ‘?’ character.
This list of parameters is called URL parameters or query parameters while the complete string after the ‘?’ character is called query string.
actual or root URL: https://www.google.com
query parameters: enc=en, auth_user=u and lan=fr
query string: ?enc=en&auth_user=u&lan=fr
- Create an empty object that will hold the query parameters.
- Retrieve the query string using window.location.search.
- Remove the starting ‘?’ by using substr function.
- Split the remaining string over ‘&’ character.
- Loop over the resulting array. Each array item will be a query parameter in key-value pair separated by ‘=’.
- Split the query parameter over ‘=’ and add first item as a key and second item as a value to the object initialized in Step 1.
// initialize an empty object let result = {}; // get URL query string let params = window.location.search; // remove the '?' character params = params.substr(1); // split the query parameters let queryParamArray = params.split('&'); // iterate over parameter array queryParamArray.forEach(function(queryParam) { // split the query parameter over '=' let item = queryParam.split('='); result[item[0]] = decodeURIComponent(item[1]); }); // print result object console.log(result);
// initialize an empty object let result = <>; // get URL query string let params = window.location.search; // remove the ‘?’ character params = params.substr(1); // split the query parameters let queryParamArray = params.split(‘&’); // iterate over parameter array queryParamArray.forEach(function(queryParam) < // split the query parameter over '=' let item = queryParam.split('='); result[item[0]] = decodeURIComponent(item[1]); >); // print result object console.log(result);
Above code when executed with a URL https://www.google.com?enc=en&auth_user=u&lan=fr prints the following output
You can use the above code as a function as given below
function getQueryParams() { // initialize an empty object let result = {}; // get URL query string let params = window.location.search; // remove the '?' character params = params.substr(1); let queryParamArray = params.split('&'); // iterate over parameter array queryParamArray.forEach(function(queryParam) { // split the query parameter over '=' let item = queryParam.split("="); result[item[0]] = decodeURIComponent(item[1]); }); // return result object return result; }
function getQueryParams() < // initialize an empty object let result = <>; // get URL query string let params = window.location.search; // remove the ‘?’ character params = params.substr(1); let queryParamArray = params.split(‘&’); // iterate over parameter array queryParamArray.forEach(function(queryParam) < // split the query parameter over '=' let item = queryParam.split("="); result[item[0]] = decodeURIComponent(item[1]); >); // return result object return result; >
Now you can easily call this function and get url parameter value by name as shown below
let parms = getQueryParams(); params('auth_user');
let parms = getQueryParams(); params(‘auth_user’);
Note that decodeURIComponent function is only required when the value of a query parameter is a URL or has characters such as : , / , [ etc.
Method 2
This method uses regular expression to create an object of key-value pairs of query parameters.
var result = {}; window.location.search .replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str, key, value) { result[key] = value; } ); console.log(result);
var result = <>; window.location.search .replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str, key, value) < resultGetting request parameters in javascript = value; >); console.log(result);
where replace method is invoked on the query string.
It takes 2 arguments. First argument is the regular expression which matches ? and & characters in the query string.
Second argument is the callback function which is invoked every time the pattern given in the regular expression is matched in the source string.
Thus, the callback function receives a query parameter every time it is invoked and it adds the key-value pair to an object.
Method 3
Use the URLSearchParams constructor and supply the query string as an argument to it. It will return an object of key-value pairs corresponding to the URL query parameters. Example,
const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); // get the required parameter const param = urlParams.get('lan'); // returns the value of parameter 'lan'
const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); // get the required parameter const param = urlParams.get(‘lan’); // returns the value of parameter ‘lan’
URLSearchParams is not supported by InternetExplorer and supported by the following browser versions
Firefox: 29 and above
Chrome: 49 and above
Edge: 17 and above
Opera: 36 and above
Safari: 10.3 and above
Hit the clap below if this post helped you in retrieving url parameters using javascript.
Share if it’s worth .
How to Get «Get» Request Parameters in JavaScript
Today’s browsers have built-in APIs for working with URLs (URL) and query strings (URLSearchParams) and these should be preferred, unless you need to support some old browsers or Opera mini (Browser support).
All data is available under
you have to parse the string, eg.
function get(name) if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
>
just call the function with GET variable name as parameter, eg.
this function will return the variables value or undefined if variable has no value or doesn’t exist
How can I get query string values in JavaScript?
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());
Update: Sep-2018
You can use URLSearchParams which is simple and has decent (but not complete) browser support.
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
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, ' '));
>
// 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)
NOTE: If a parameter is present several times ( ?foo=lorem&foo=ipsum ), you will get the first value ( lorem ). There is no standard about this and usages vary, see for example this question: Authoritative position of duplicate HTTP GET query keys.
NOTE: The function is case-sensitive. If you prefer case-insensitive parameter name, add ‘i’ modifier to RegExp
NOTE: If you’re getting a no-useless-escape eslint error, you can replace name = name.replace(/[\[\]]/g, ‘\\$&’); with name = name.replace(/[[\]]/g, ‘\\$&’) .
This is an update based on the new URLSearchParams specs to achieve the same result more succinctly. See answer titled «URLSearchParams» below.
How to get URL parameter using jQuery or plain JavaScript?
var getUrlParameter = function getUrlParameter(sParam) var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
>
>
return false;
>;
And this is how you can use this function assuming the URL is,
var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');
Get the values from the GET parameters (JavaScript)
JavaScript itself has nothing built in for handling query string parameters.
Code running in a (modern) browser can use the URL object (a Web API). URL is also implemented by Node.js:
// You can get url_string from window.location.href if you want to work with
// the URL of the current page
var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5";
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);
How to retrieve GET parameters from JavaScript
With the window.location object. This code gives you GET without the question mark.
window.location.search.substr(1)
From your example it will return returnurl=%2Fadmin
EDIT: I took the liberty of changing Qwerty’s answer, which is really good, and as he pointed I followed exactly what the OP asked:
function findGetParameter(parameterName) var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) tmp = item.split(" &");
for (var index = 0; index < items.length; index++) tmp = items[index].split(" https://geo.example.org/api"),
params =
Object.keys(params).forEach(key => url.searchParams.append(key, paramsGetting request parameters in javascript))
fetch(url).then(/* … */)
However, I’m not sure Chrome supports the searchParams property of a URL (at the time of writing) so you might want to either use a third party library or roll-your-own solution.
Update April 2018:
With the use of URLSearchParams constructor you could assign a 2D array or a object and just assign that to the url.search instead of looping over all keys and append them
var url = new URL('https://sl.se')
var params = // or:
var params = [['lat', '35.696233'], ['long', '139.570431']]
url.search = new URLSearchParams(params).toString();
fetch(url)
Sidenote: URLSearchParams is also available in NodeJS
How to pass parameters in GET requests with jQuery
Use data option of ajax. You can send data object to server by data option in ajax and the type which defines how you are sending it (either POST or GET ). The default type is GET method
$.ajax( url: "ajax.aspx",
type: "get", //send it through get method
data: <
ajaxid: 4,
UserID: UserID,
EmailAddress: EmailAddress
>,
success: function(response) //Do Something
>,
error: function(xhr) //Do Something to handle error
>
>);
And you can get the data by (if you are using PHP)
$_GET['ajaxid'] //gives 4
$_GET['UserID'] //gives you the sent userid
In aspx, I believe it is (might be wrong)
Request.QueryString["ajaxid"].ToString();
How to retrieve query parameters from GET request using javascript?
If this is on the client you can use URL and searchParams
// const url = new URL(location.href); // uncomment and delete next line
const url = new URL("https://sdkapp.example.com:8443/central-login/index.html?client_id=dtvClient&redirect_uri=https://www.example3.com:443/callback"); // for example
const obj = "clientId": url.searchParams.get("client_id"),
"redirectUri": url.searchParams.get("redirect_uri")
>;
console.log(obj)
// Config.set(obj)
Getting the url parameters inside the html page
A nice solution is given here:
function GetURLParameter(sParam)
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
return sParameterName[1];
>
>
>
And this is how you can use this function assuming the URL is,
http://dummy.com/?technology=jquery&blog=jquerybyexample :
var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');`