Get escaped URL parameter - javascript

I'm looking for a jQuery plugin that can get URL parameters, and support this search string without outputting the JavaScript error: "malformed URI sequence". If there isn't a jQuery plugin that supports this, I need to know how to modify it to support this.
?search=%E6%F8%E5
The value of the URL parameter, when decoded, should be:
æøå
(the characters are Norwegian).
I don't have access to the server, so I can't modify anything on it.

function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}

Below is what I have created from the comments here, as well as fixing bugs not mentioned (such as actually returning null, and not 'null'):
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

What you really want is the jQuery URL Parser plugin. With this plugin, getting the value of a specific URL parameter (for the current URL) looks like this:
$.url().param('foo');
If you want an object with parameter names as keys and parameter values as values, you'd just call param() without an argument, like this:
$.url().param();
This library also works with other urls, not just the current one:
$.url('http://allmarkedup.com?sky=blue&grass=green').param();
$('#myElement').url().param(); // works with elements that have 'src', 'href' or 'action' attributes
Since this is an entire URL parsing library, you can also get other information from the URL, like the port specified, or the path, protocol etc:
var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value');
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'
It has other features as well, check out its homepage for more docs and examples.
Instead of writing your own URI parser for this specific purpose that kinda works in most cases, use an actual URI parser. Depending on the answer, code from other answers can return 'null' instead of null, doesn't work with empty parameters (?foo=&bar=x), can't parse and return all parameters at once, repeats the work if you repeatedly query the URL for parameters etc.
Use an actual URI parser, don't invent your own.
For those averse to jQuery, there's a version of the plugin that's pure JS.

If you don't know what the URL parameters will be and want to get an object with the keys and values that are in the parameters, you can use this:
function getParameters() {
var searchString = window.location.search.substring(1),
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
return hash;
}
Calling getParameters() with a url like /posts?date=9/10/11&author=nilbus would return:
{
date: '9/10/11',
author: 'nilbus'
}
I won't include the code here since it's even farther away from the question, but weareon.net posted a library that allows manipulation of the parameters in the URL too:
Blog post: http://blog.weareon.net/working-with-url-parameters-in-javascript/
Code: http://pastebin.ubuntu.com/1163515/

You can use the browser native location.search property:
function getParameter(paramName) {
var searchString = window.location.search.substring(1),
i, val, params = searchString.split("&");
for (i=0;i<params.length;i++) {
val = params[i].split("=");
if (val[0] == paramName) {
return unescape(val[1]);
}
}
return null;
}
But there are some jQuery plugins that can help you:
query-object
getURLParam

Based on the 999's answer:
function getURLParameter(name) {
return decodeURIComponent(
(location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
);
}
Changes:
decodeURI() is replaced with decodeURIComponent()
[?|&] is added at the beginning of the regexp

Need to add the i parameter to make it case insensitive:
function getURLParameter(name) {
return decodeURIComponent(
(RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
);
}

After reading all of the answers I ended up with this version with + a second function to use parameters as flags
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)','i').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
function isSetURLParameter(name) {
return (new RegExp('[?|&]' + name + '(?:[=|&|#|;|]|$)','i').exec(location.search) !== null)
}

$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(top.window.location.href);
return (results !== null) ? results[1] : 0;
}
$.urlParam("key");

For example , a function which returns value of any parameters variable.
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://example.com/?technology=jquery&blog=jquerybyexample".
var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');
So in above code variable "tech" will have "jQuery" as value and "blog" variable's will be "jquerybyexample".

You should not use jQuery for something like this!
The modern way is to use small reusable modules through a package-manager like Bower.
I've created a tiny module that can parse the query string into an object. Use it like this:
// parse the query string into an object and get the property
queryString.parse(unescape(location.search)).search;
//=> æøå

There's a lot of buggy code here and regex solutions are very slow. I found a solution that works up to 20x faster than the regex counterpart and is elegantly simple:
/*
* #param string parameter to return the value of.
* #return string value of chosen parameter, if found.
*/
function get_param(return_this)
{
return_this = return_this.replace(/\?/ig, "").replace(/=/ig, ""); // Globally replace illegal chars.
var url = window.location.href; // Get the URL.
var parameters = url.substring(url.indexOf("?") + 1).split("&"); // Split by "param=value".
var params = []; // Array to store individual values.
for(var i = 0; i < parameters.length; i++)
if(parameters[i].search(return_this + "=") != -1)
return parameters[i].substring(parameters[i].indexOf("=") + 1).split("+");
return "Parameter not found";
}
console.log(get_param("parameterName"));
Regex is not the be-all and end-all solution, for this type of problem simple string manipulation can work a huge amount more efficiently. Code source.

<script type="text/javascript">
function getURLParameter(name) {
return decodeURIComponent(
(location.search.toLowerCase().match(RegExp("[?|&]" + name + '=(.+?)(&|$)')) || [, null])[1]
);
}
</script>
getURLParameter(id) or getURLParameter(Id) Works the same : )

jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
//example params with spaces
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));
//output: Gold%20Coast
console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast

function getURLParameters(paramName)
{
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i=0;i<arrURLParams.length;i++)
{
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i=0;i<arrURLParams.length;i++)
{
if(arrParamNames[i] == paramName){
//alert("Param:"+arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}

I created a simple function to get URL parameter in JavaScript from a URL like this:
.....58e/web/viewer.html?page=*17*&getinfo=33
function buildLinkb(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=parseInt(url.replace(param+"=",""));
alert(n+1);
}
buildLinkb("page");
OUTPUT: 18

Just in case you guys have the url like localhost/index.xsp?a=1#something and you need to get the param not the hash.
var vars = [], hash, anchor;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
anchor = hash[1].split('#');
vars.push(anchor[0]);
vars[hash[0]] = anchor[0];
}
}

Slight modification to the answer by #pauloppenheim , as it will not properly handle parameter names which can be a part of other parameter names.
Eg: If you have "appenv" & "env" parameters, redeaing the value for "env" can pick-up "appenv" value.
Fix:
var urlParamVal = function (name) {
var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
return result ? decodeURIComponent(result[2]) : "";
};

This may help.
<script type="text/javascript">
$(document).ready(function(){
alert(getParameterByName("third"));
});
function getParameterByName(name){
var url = document.URL,
count = url.indexOf(name);
sub = url.substring(count);
amper = sub.indexOf("&");
if(amper == "-1"){
var param = sub.split("=");
return param[1];
}else{
var param = sub.substr(0,amper).split("=");
return param[1];
}
}
</script>

Related

How to read URL Query Parameter where value has + for spaces [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 1 year ago.
I have a URL with some GET parameters as follows:
www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
I need to get the whole value of c. I tried to read the URL, but I got only m2. How do I do this using 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);
For older browsers (including Internet Explorer), you can use this polyfill.
You could also use one for URLSearchParams and extract the query string to pass to it with window.location.search.substring(1).
You could also use the code from the original version of this answer that predates URL. The above polyfill is robust and well tested and I strongly recommend it over this though.
You could access location.search, which would give you from the ? character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.
Then you can parse it with this:
function parse_query_string(query) {
var vars = query.split("&");
var query_string = {};
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
var key = decodeURIComponent(pair.shift());
var value = decodeURIComponent(pair.join("="));
// If first entry with this name
if (typeof query_string[key] === "undefined") {
query_string[key] = value;
// If second entry with this name
} else if (typeof query_string[key] === "string") {
var arr = [query_string[key], value];
query_string[key] = arr;
// If third or later entry with this name
} else {
query_string[key].push(value);
}
}
return query_string;
}
var query_string = "a=1&b=3&c=m2-m3-m4-m5";
var parsed_qs = parse_query_string(query_string);
console.log(parsed_qs.c);
You can get the query string from the URL of the current page with:
var query = window.location.search.substring(1);
var qs = parse_query_string(query);
Most implementations I've seen miss out URL-decoding the names and the values.
Here's a general utility function that also does proper URL-decoding:
function getQueryParams(qs) {
qs = qs.split('+').join(' ');
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
//var query = getQueryParams(document.location.search);
//alert(query.foo);
source
function gup( name, url ) {
if (!url) url = location.href;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
return results == null ? null : results[1];
}
gup('q', 'hxxp://example.com/?q=abc')
This is an easy way to check just one parameter:
Example URL:
http://myserver/action?myParam=2
Example Javascript:
var myParam = location.search.split('myParam=')[1]
if "myParam" exists in the URL... variable myParam will contain "2", otherwise it will be undefined.
Maybe you want a default value, in that case:
var myParam = location.search.split('myParam=')[1] ? location.search.split('myParam=')[1] : 'myDefaultValue';
Update: This works better:
var url = "http://www.example.com/index.php?myParam=384&login=admin"; // or window.location.href for current url
var captured = /myParam=([^&]+)/.exec(url)[1]; // Value is in [1] ('384' in our case)
var result = captured ? captured : 'myDefaultValue';
And it works right even when URL is full of parameters.
Browsers vendors have implemented a native way to do this via URL and URLSearchParams.
let url = new URL('http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5');
let searchParams = new URLSearchParams(url.search);
console.log(searchParams.get('c')); // outputs "m2-m3-m4-m5"
Currently supported in Firefox, Opera, Safari, Chrome and Edge. For a list of browser support see here.
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
https://developer.mozilla.org/en-US/docs/Web/API/URL/URL
https://url.spec.whatwg.org/
Eric Bidelman, an engineer at Google, recommends using this polyfill for unsupported browsers.
I found this ages ago, very easy:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
Then call it like this:
var fType = getUrlVars()["type"];
You can get the query string in location.search, then you can split everything after the question mark:
var params = {};
if (location.search) {
var parts = location.search.substring(1).split('&');
for (var i = 0; i < parts.length; i++) {
var nv = parts[i].split('=');
if (!nv[0]) continue;
params[nv[0]] = nv[1] || true;
}
}
// Now you can get the parameters you want like so:
var abc = params.abc;
A super simple way using URLSearchParams.
function getParam(param){
return new URLSearchParams(window.location.search).get(param);
}
It's currently supported in Chrome, Firefox, Safari, Edge, and others.
I wrote a more simple and elegant solution.
var arr = document.URL.match(/room=([0-9]+)/)
var room = arr[1];
Here is a recursive solution that has no regex, and has minimal mutation (only the params object is mutated, which I believe is unavoidable in JS).
It's awesome because it:
Is recursive
Handles multiple parameters of the same name
Deals well with malformed parameter strings (missing values, so on)
Doesn't break if '=' is in the value
Performs URL decoding
And lastly, It's awesome because it...argh!!!
Code:
var get_params = function(search_string) {
var parse = function(params, pairs) {
var pair = pairs[0];
var parts = pair.split('=');
var key = decodeURIComponent(parts[0]);
var value = decodeURIComponent(parts.slice(1).join('='));
// Handle multiple parameters of the same name
if (typeof params[key] === "undefined") {
params[key] = value;
} else {
params[key] = [].concat(params[key], value);
}
return pairs.length == 1 ? params : parse(params, pairs.slice(1))
}
// Get rid of leading ?
return search_string.length == 0 ? {} : parse({}, search_string.substr(1).split('&'));
}
var params = get_params(location.search);
// Finally, to get the param you want
params['c'];
I made a function that does this:
var getUrlParams = function (url) {
var params = {};
(url + '?').split('?')[1].split('&').forEach(function (pair) {
pair = (pair + '=').split('=').map(decodeURIComponent);
if (pair[0].length) {
params[pair[0]] = pair[1];
}
});
return params;
};
Update 5/26/2017, here is an ES7 implementation (runs with babel preset stage 0, 1, 2, or 3):
const getUrlParams = url => `${url}?`.split('?')[1]
.split('&').reduce((params, pair) =>
((key, val) => key ? {...params, [key]: val} : params)
(...`${pair}=`.split('=').map(decodeURIComponent)), {});
Some tests:
console.log(getUrlParams('https://google.com/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('https://google.com/')); // Will log {}
console.log(getUrlParams('a=1&b=2&c')); // Will log {}
Update 3/26/2018, here is a Typescript implementation:
const getUrlParams = (search: string) => `${search}?`
.split('?')[1]
.split('&')
.reduce(
(params: object, pair: string) => {
const [key, value] = `${pair}=`
.split('=')
.map(decodeURIComponent)
return key.length > 0 ? { ...params, [key]: value } : params
},
{}
)
Update 2/13/2019, here is an updated TypeScript implementation that works with TypeScript 3.
interface IParams { [key: string]: string }
const paramReducer = (params: IParams, pair: string): IParams => {
const [key, value] = `${pair}=`.split('=').map(decodeURIComponent)
return key.length > 0 ? { ...params, [key]: value } : params
}
const getUrlParams = (search: string): IParams =>
`${search}?`.split('?')[1].split('&').reduce<IParams>(paramReducer, {})
See this
function getURLParameters(paramName)
{
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i<arrURLParams.length; i++)
{
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i=0; i<arrURLParams.length; i++)
{
if (arrParamNames[i] == paramName)
{
//alert("Parameter:" + arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
The shortest way:
new URL(location.href).searchParams.get("my_key");
ECMAScript 6 solution:
var params = window.location.search
.substring(1)
.split("&")
.map(v => v.split("="))
.reduce((map, [key, value]) => map.set(key, decodeURIComponent(value)), new Map())
I use the parseUri library. It allows you to do exactly what you are asking for:
var uri = 'www.test.com/t.html&a=1&b=3&c=m2-m3-m4-m5';
var c = uri.queryKey['c'];
// c = 'm2-m3-m4-m5'
I use
function getVal(str) {
var v = window.location.search.match(new RegExp('(?:[\?\&]'+str+'=)([^&]+)'));
return v ? v[1] : null;
}
this question has too many answers, so i'm adding another one.
/**
* parses and returns URI query parameters
*
* #param {string} param parm
* #param {bool?} asArray if true, returns an array instead of a scalar
* #returns {Object|Array}
*/
function getURIParameter(param, asArray) {
return document.location.search.substring(1).split('&').reduce(function(p,c) {
var parts = c.split('=', 2).map(function(param) { return decodeURIComponent(param); });
if(parts.length == 0 || parts[0] != param) return (p instanceof Array) && !asArray ? null : p;
return asArray ? p.concat(parts.concat(true)[1]) : parts.concat(true)[1];
}, []);
}
usage:
getURIParameter("id") // returns the last id or null if not present
getURIParameter("id", true) // returns an array of all ids
this copes with empty parameters (those keys present without "=value"), exposure of both a scalar and array-based value retrieval API, as well as proper URI component decoding.
Here is my solution. As advised by Andy E while answering this question, it's not good for your script's performance if it's repeatedly building various regex strings, running loops etc just to get a single value. So, I've come up with a simpler script that returns all the GET parameters in a single object. You should call it just once, assign the result to a variable and then, at any point in the future, get any value you want from that variable using the appropriate key. Note that it also takes care of URI decoding (i.e things like %20) and replaces + with a space:
function getUrlQueryParams(url) {
var queryString = url.split("?")[1];
var keyValuePairs = queryString.split("&");
var keyValue = [];
var queryParams = {};
keyValuePairs.forEach(function(pair) {
keyValue = pair.split("=");
queryParams[keyValue[0]] = decodeURIComponent(keyValue[1]).replace(/\+/g, " ");
});
return queryParams;
}
So, here are are a few tests of the script for you to see:
// Query parameters with strings only, no special characters.
var currentParams = getUrlQueryParams("example.com/foo?number=zero");
alert(currentParams["number"]); // Gives "zero".
// For the URL you stated above...
var someParams = getUrlQueryParams("www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 ");
alert(someParams["c"]); // Gives "m2-m3-m4-m5".
// For a query params with URI encoding...
var someParams = getUrlQueryParams("www.example.com/t.html?phrase=a%20long%20shot&location=Silicon+Valley%2C+USA");
alert(someParams["phrase"]); // Gives "a long shot".
alert(someParams["location"]); // Gives "Silicon Valley, USA".
The easiest way using the replace() method:
From the urlStr string:
paramVal = urlStr.replace(/.*param_name=([^&]*).*|(.*)/, '$1');
or from the current URL:
paramVal = document.URL.replace(/.*param_name=([^&]*).*|(.*)/, '$1');
Explanation:
document.URL - interface returns the document location (page url) as a string.
replace() - method returns a new string with some or all matches of a pattern replaced by a replacement.
/.*param_name=([^&]*).*/ - the regular expression pattern enclosed between slashes which means:
.* - zero or more of any characters,
param_name= - param name which is serched,
() - group in regular expression,
[^&]* - one or more of any characters excluding &,
| - alternation,
$1 - reference to first group in regular expression.
var urlStr = 'www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5';
var c = urlStr.replace(/.*c=([^&]*).*|(.*)/, '$1');
var notExisted = urlStr.replace(/.*not_existed=([^&]*).*|(.*)/, '$1');
console.log(`c === '${c}'`);
console.log(`notExisted === '${notExisted}'`);
Yet another suggestion.
There are some good answers already, but I found them needlessly complex and hard to understand. This is short, simple, and returns a simple associative array with key names corresponding to the token names in the URL.
I added a version with comments below for those who want to learn.
Note this relies on jQuery ($.each) for its loop, which I recommend instead of forEach. I find it simpler to ensure cross-browser compatibility using jQuery across the board rather than plugging in individual fixes to support whichever new functions aren't supported in older browsers.
Edit: After I wrote this I noticed Eric Elliott's answer, which is almost the same, though it uses forEach, while I'm generally against (for reasons stated above).
function getTokens(){
var tokens = [];
var query = location.search;
query = query.slice(1);
query = query.split('&');
$.each(query, function(i,value){
var token = value.split('=');
var key = decodeURIComponent(token[0]);
var data = decodeURIComponent(token[1]);
tokens[key] = data;
});
return tokens;
}
Commented version:
function getTokens(){
var tokens = []; // new array to hold result
var query = location.search; // everything from the '?' onward
query = query.slice(1); // remove the first character, which will be the '?'
query = query.split('&'); // split via each '&', leaving us an array of something=something strings
// iterate through each something=something string
$.each(query, function(i,value){
// split the something=something string via '=', creating an array containing the token name and data
var token = value.split('=');
// assign the first array element (the token name) to the 'key' variable
var key = decodeURIComponent(token[0]);
// assign the second array element (the token data) to the 'data' variable
var data = decodeURIComponent(token[1]);
tokens[key] = data; // add an associative key/data pair to our result array, with key names being the URI token names
});
return tokens; // return the array
}
For the examples below we'll assume this address:
http://www.example.com/page.htm?id=4&name=murray
You can assign the URL tokens to your own variable:
var tokens = getTokens();
Then refer to each URL token by name like this:
document.write( tokens['id'] );
This would print "4".
You can also simply refer to a a token name from the function directly:
document.write( getTokens()['name'] );
...which would print "murray".
Or if you don't want to reinvent the URI parsing wheel use URI.js
To get the value of a parameter named foo:
new URI((''+document.location)).search(true).foo
What that does is
Convert document.location to a string (it's an object)
Feed that string to URI.js's URI class construtor
Invoke the search() function to get the search (query) portion of the url
(passing true tells it to output an object)
Access the foo property on the resulting object to get the value
Here's a fiddle for this.... http://jsfiddle.net/m6tett01/12/
For Single Parameter Value like this index.html?msg=1 use following code,
$(window).load(function(){
queryString();
});
function queryString()
{
var queryString = window.location.search.substring(1);
var varArray = queryString.split("="); //eg. index.html?msg=1
var param1 = varArray[0];
var param2 = varArray[1];
}
For All Parameter Value use following Code,
$(window).load(function(){
queryString();
});
function queryString()
{
var queryString = window.location.search;
var varArray = queryString.split("&");
for (var i=0;i<varArray.length;i++) {
var param = varArray[i].split("=");
//parameter-value pair
}
}
Here I am posting one example. But it's in jQuery. Hope it will help others:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>
<!-- URL: www.example.com/correct/?message=done&year=1990-->
<script type="text/javascript">
$(function(){
$.url.attr('protocol') // --> Protocol: "http"
$.url.attr('path') // --> host: "www.example.com"
$.url.attr('query') // --> path: "/correct/"
$.url.attr('message') // --> query: "done"
$.url.attr('year') // --> query: "1990"
});
</script>
I had the need to read a URL GET variable and complete an action based on the url parameter. I searched high and low for a solution and came across this little piece of code. It basically reads the current page url, perform some regular expression on the URL then saves the url parameters in an associative array, which we can easily access.
So as an example if we had the following url with the javascript at the bottom in place.
http://TestServer/Pages/NewsArchive.aspx?year=2013&Month=July
All we’d need to do to get the parameters id and page are to call this:
The Code will be:
<script type="text/javascript">
var first = getUrlVars()["year"];
var second = getUrlVars()["Month"];
alert(first);
alert(second);
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
// Usage for URL: http://my.site.com/location?locationId=53cc272c0364aefcb78756cd&shared=false
var id = getUrlVars()["locationId"];
Got from here: http://jquery-howto.blogspot.ru/2009/09/get-url-parameters-values-with-jquery.html
Simple way
function getParams(url){
var regex = /[?&]([^=#]+)=([^&#]*)/g,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
return params;
}
then call it like getParams(url)
Elegant, functional style solution
Let's create an object containing URL param names as keys, then we can easily extract the parameter by its name:
// URL: https://example.com/?test=true&orderId=9381
// Build an object containing key-value pairs
export const queryStringParams = window.location.search
.split('?')[1]
.split('&')
.map(keyValue => keyValue.split('='))
.reduce<QueryStringParams>((params, [key, value]) => {
params[key] = value;
return params;
}, {});
type QueryStringParams = {
[key: string]: string;
};
// Return URL parameter called "orderId"
return queryStringParams.orderId;
It's the N++ time I am looking for a clean way to do this.
Will save this here in case I get back cause I know I will... 🙄
const parseUrlQuery = (value) => {
var urlParams = new URL(value).searchParams
return Array.from(urlParams.keys()).reduce((acc, key) => {
acc[key] = urlParams.getAll(key)
return acc
}, {})
}
console.log(parseUrlQuery('http://url/path?param1=A&param1=B&param2=ABC&param3=61569'))
Here is what I do:
var uriParams = getSearchParameters();
alert(uriParams.c);
// background functions:
// Get object/associative array of URL parameters
function getSearchParameters () {
var prmstr = window.location.search.substr(1);
return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}
// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
var params = {},
prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
// http:localhost:8080/path?param_1=a&param_2=b
var getParamsMap = function () {
var params = window.location.search.split("&");
var paramsMap = {};
params.forEach(function (p) {
var v = p.split("=");
paramsMap[v[0]]=decodeURIComponent(v[1]);
});
return paramsMap;
};
// -----------------------
console.log(getParamsMap()["param_1"]); // should log "a"

Get Facebook referal in Chrome extension [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 1 year ago.
I have a URL with some GET parameters as follows:
www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
I need to get the whole value of c. I tried to read the URL, but I got only m2. How do I do this using 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);
For older browsers (including Internet Explorer), you can use this polyfill.
You could also use one for URLSearchParams and extract the query string to pass to it with window.location.search.substring(1).
You could also use the code from the original version of this answer that predates URL. The above polyfill is robust and well tested and I strongly recommend it over this though.
You could access location.search, which would give you from the ? character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.
Then you can parse it with this:
function parse_query_string(query) {
var vars = query.split("&");
var query_string = {};
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
var key = decodeURIComponent(pair.shift());
var value = decodeURIComponent(pair.join("="));
// If first entry with this name
if (typeof query_string[key] === "undefined") {
query_string[key] = value;
// If second entry with this name
} else if (typeof query_string[key] === "string") {
var arr = [query_string[key], value];
query_string[key] = arr;
// If third or later entry with this name
} else {
query_string[key].push(value);
}
}
return query_string;
}
var query_string = "a=1&b=3&c=m2-m3-m4-m5";
var parsed_qs = parse_query_string(query_string);
console.log(parsed_qs.c);
You can get the query string from the URL of the current page with:
var query = window.location.search.substring(1);
var qs = parse_query_string(query);
Most implementations I've seen miss out URL-decoding the names and the values.
Here's a general utility function that also does proper URL-decoding:
function getQueryParams(qs) {
qs = qs.split('+').join(' ');
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
//var query = getQueryParams(document.location.search);
//alert(query.foo);
source
function gup( name, url ) {
if (!url) url = location.href;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
return results == null ? null : results[1];
}
gup('q', 'hxxp://example.com/?q=abc')
This is an easy way to check just one parameter:
Example URL:
http://myserver/action?myParam=2
Example Javascript:
var myParam = location.search.split('myParam=')[1]
if "myParam" exists in the URL... variable myParam will contain "2", otherwise it will be undefined.
Maybe you want a default value, in that case:
var myParam = location.search.split('myParam=')[1] ? location.search.split('myParam=')[1] : 'myDefaultValue';
Update: This works better:
var url = "http://www.example.com/index.php?myParam=384&login=admin"; // or window.location.href for current url
var captured = /myParam=([^&]+)/.exec(url)[1]; // Value is in [1] ('384' in our case)
var result = captured ? captured : 'myDefaultValue';
And it works right even when URL is full of parameters.
Browsers vendors have implemented a native way to do this via URL and URLSearchParams.
let url = new URL('http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5');
let searchParams = new URLSearchParams(url.search);
console.log(searchParams.get('c')); // outputs "m2-m3-m4-m5"
Currently supported in Firefox, Opera, Safari, Chrome and Edge. For a list of browser support see here.
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
https://developer.mozilla.org/en-US/docs/Web/API/URL/URL
https://url.spec.whatwg.org/
Eric Bidelman, an engineer at Google, recommends using this polyfill for unsupported browsers.
I found this ages ago, very easy:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
Then call it like this:
var fType = getUrlVars()["type"];
You can get the query string in location.search, then you can split everything after the question mark:
var params = {};
if (location.search) {
var parts = location.search.substring(1).split('&');
for (var i = 0; i < parts.length; i++) {
var nv = parts[i].split('=');
if (!nv[0]) continue;
params[nv[0]] = nv[1] || true;
}
}
// Now you can get the parameters you want like so:
var abc = params.abc;
A super simple way using URLSearchParams.
function getParam(param){
return new URLSearchParams(window.location.search).get(param);
}
It's currently supported in Chrome, Firefox, Safari, Edge, and others.
I wrote a more simple and elegant solution.
var arr = document.URL.match(/room=([0-9]+)/)
var room = arr[1];
Here is a recursive solution that has no regex, and has minimal mutation (only the params object is mutated, which I believe is unavoidable in JS).
It's awesome because it:
Is recursive
Handles multiple parameters of the same name
Deals well with malformed parameter strings (missing values, so on)
Doesn't break if '=' is in the value
Performs URL decoding
And lastly, It's awesome because it...argh!!!
Code:
var get_params = function(search_string) {
var parse = function(params, pairs) {
var pair = pairs[0];
var parts = pair.split('=');
var key = decodeURIComponent(parts[0]);
var value = decodeURIComponent(parts.slice(1).join('='));
// Handle multiple parameters of the same name
if (typeof params[key] === "undefined") {
params[key] = value;
} else {
params[key] = [].concat(params[key], value);
}
return pairs.length == 1 ? params : parse(params, pairs.slice(1))
}
// Get rid of leading ?
return search_string.length == 0 ? {} : parse({}, search_string.substr(1).split('&'));
}
var params = get_params(location.search);
// Finally, to get the param you want
params['c'];
I made a function that does this:
var getUrlParams = function (url) {
var params = {};
(url + '?').split('?')[1].split('&').forEach(function (pair) {
pair = (pair + '=').split('=').map(decodeURIComponent);
if (pair[0].length) {
params[pair[0]] = pair[1];
}
});
return params;
};
Update 5/26/2017, here is an ES7 implementation (runs with babel preset stage 0, 1, 2, or 3):
const getUrlParams = url => `${url}?`.split('?')[1]
.split('&').reduce((params, pair) =>
((key, val) => key ? {...params, [key]: val} : params)
(...`${pair}=`.split('=').map(decodeURIComponent)), {});
Some tests:
console.log(getUrlParams('https://google.com/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('https://google.com/')); // Will log {}
console.log(getUrlParams('a=1&b=2&c')); // Will log {}
Update 3/26/2018, here is a Typescript implementation:
const getUrlParams = (search: string) => `${search}?`
.split('?')[1]
.split('&')
.reduce(
(params: object, pair: string) => {
const [key, value] = `${pair}=`
.split('=')
.map(decodeURIComponent)
return key.length > 0 ? { ...params, [key]: value } : params
},
{}
)
Update 2/13/2019, here is an updated TypeScript implementation that works with TypeScript 3.
interface IParams { [key: string]: string }
const paramReducer = (params: IParams, pair: string): IParams => {
const [key, value] = `${pair}=`.split('=').map(decodeURIComponent)
return key.length > 0 ? { ...params, [key]: value } : params
}
const getUrlParams = (search: string): IParams =>
`${search}?`.split('?')[1].split('&').reduce<IParams>(paramReducer, {})
See this
function getURLParameters(paramName)
{
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i<arrURLParams.length; i++)
{
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i=0; i<arrURLParams.length; i++)
{
if (arrParamNames[i] == paramName)
{
//alert("Parameter:" + arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
The shortest way:
new URL(location.href).searchParams.get("my_key");
ECMAScript 6 solution:
var params = window.location.search
.substring(1)
.split("&")
.map(v => v.split("="))
.reduce((map, [key, value]) => map.set(key, decodeURIComponent(value)), new Map())
I use the parseUri library. It allows you to do exactly what you are asking for:
var uri = 'www.test.com/t.html&a=1&b=3&c=m2-m3-m4-m5';
var c = uri.queryKey['c'];
// c = 'm2-m3-m4-m5'
I use
function getVal(str) {
var v = window.location.search.match(new RegExp('(?:[\?\&]'+str+'=)([^&]+)'));
return v ? v[1] : null;
}
this question has too many answers, so i'm adding another one.
/**
* parses and returns URI query parameters
*
* #param {string} param parm
* #param {bool?} asArray if true, returns an array instead of a scalar
* #returns {Object|Array}
*/
function getURIParameter(param, asArray) {
return document.location.search.substring(1).split('&').reduce(function(p,c) {
var parts = c.split('=', 2).map(function(param) { return decodeURIComponent(param); });
if(parts.length == 0 || parts[0] != param) return (p instanceof Array) && !asArray ? null : p;
return asArray ? p.concat(parts.concat(true)[1]) : parts.concat(true)[1];
}, []);
}
usage:
getURIParameter("id") // returns the last id or null if not present
getURIParameter("id", true) // returns an array of all ids
this copes with empty parameters (those keys present without "=value"), exposure of both a scalar and array-based value retrieval API, as well as proper URI component decoding.
Here is my solution. As advised by Andy E while answering this question, it's not good for your script's performance if it's repeatedly building various regex strings, running loops etc just to get a single value. So, I've come up with a simpler script that returns all the GET parameters in a single object. You should call it just once, assign the result to a variable and then, at any point in the future, get any value you want from that variable using the appropriate key. Note that it also takes care of URI decoding (i.e things like %20) and replaces + with a space:
function getUrlQueryParams(url) {
var queryString = url.split("?")[1];
var keyValuePairs = queryString.split("&");
var keyValue = [];
var queryParams = {};
keyValuePairs.forEach(function(pair) {
keyValue = pair.split("=");
queryParams[keyValue[0]] = decodeURIComponent(keyValue[1]).replace(/\+/g, " ");
});
return queryParams;
}
So, here are are a few tests of the script for you to see:
// Query parameters with strings only, no special characters.
var currentParams = getUrlQueryParams("example.com/foo?number=zero");
alert(currentParams["number"]); // Gives "zero".
// For the URL you stated above...
var someParams = getUrlQueryParams("www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 ");
alert(someParams["c"]); // Gives "m2-m3-m4-m5".
// For a query params with URI encoding...
var someParams = getUrlQueryParams("www.example.com/t.html?phrase=a%20long%20shot&location=Silicon+Valley%2C+USA");
alert(someParams["phrase"]); // Gives "a long shot".
alert(someParams["location"]); // Gives "Silicon Valley, USA".
The easiest way using the replace() method:
From the urlStr string:
paramVal = urlStr.replace(/.*param_name=([^&]*).*|(.*)/, '$1');
or from the current URL:
paramVal = document.URL.replace(/.*param_name=([^&]*).*|(.*)/, '$1');
Explanation:
document.URL - interface returns the document location (page url) as a string.
replace() - method returns a new string with some or all matches of a pattern replaced by a replacement.
/.*param_name=([^&]*).*/ - the regular expression pattern enclosed between slashes which means:
.* - zero or more of any characters,
param_name= - param name which is serched,
() - group in regular expression,
[^&]* - one or more of any characters excluding &,
| - alternation,
$1 - reference to first group in regular expression.
var urlStr = 'www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5';
var c = urlStr.replace(/.*c=([^&]*).*|(.*)/, '$1');
var notExisted = urlStr.replace(/.*not_existed=([^&]*).*|(.*)/, '$1');
console.log(`c === '${c}'`);
console.log(`notExisted === '${notExisted}'`);
Yet another suggestion.
There are some good answers already, but I found them needlessly complex and hard to understand. This is short, simple, and returns a simple associative array with key names corresponding to the token names in the URL.
I added a version with comments below for those who want to learn.
Note this relies on jQuery ($.each) for its loop, which I recommend instead of forEach. I find it simpler to ensure cross-browser compatibility using jQuery across the board rather than plugging in individual fixes to support whichever new functions aren't supported in older browsers.
Edit: After I wrote this I noticed Eric Elliott's answer, which is almost the same, though it uses forEach, while I'm generally against (for reasons stated above).
function getTokens(){
var tokens = [];
var query = location.search;
query = query.slice(1);
query = query.split('&');
$.each(query, function(i,value){
var token = value.split('=');
var key = decodeURIComponent(token[0]);
var data = decodeURIComponent(token[1]);
tokens[key] = data;
});
return tokens;
}
Commented version:
function getTokens(){
var tokens = []; // new array to hold result
var query = location.search; // everything from the '?' onward
query = query.slice(1); // remove the first character, which will be the '?'
query = query.split('&'); // split via each '&', leaving us an array of something=something strings
// iterate through each something=something string
$.each(query, function(i,value){
// split the something=something string via '=', creating an array containing the token name and data
var token = value.split('=');
// assign the first array element (the token name) to the 'key' variable
var key = decodeURIComponent(token[0]);
// assign the second array element (the token data) to the 'data' variable
var data = decodeURIComponent(token[1]);
tokens[key] = data; // add an associative key/data pair to our result array, with key names being the URI token names
});
return tokens; // return the array
}
For the examples below we'll assume this address:
http://www.example.com/page.htm?id=4&name=murray
You can assign the URL tokens to your own variable:
var tokens = getTokens();
Then refer to each URL token by name like this:
document.write( tokens['id'] );
This would print "4".
You can also simply refer to a a token name from the function directly:
document.write( getTokens()['name'] );
...which would print "murray".
Or if you don't want to reinvent the URI parsing wheel use URI.js
To get the value of a parameter named foo:
new URI((''+document.location)).search(true).foo
What that does is
Convert document.location to a string (it's an object)
Feed that string to URI.js's URI class construtor
Invoke the search() function to get the search (query) portion of the url
(passing true tells it to output an object)
Access the foo property on the resulting object to get the value
Here's a fiddle for this.... http://jsfiddle.net/m6tett01/12/
For Single Parameter Value like this index.html?msg=1 use following code,
$(window).load(function(){
queryString();
});
function queryString()
{
var queryString = window.location.search.substring(1);
var varArray = queryString.split("="); //eg. index.html?msg=1
var param1 = varArray[0];
var param2 = varArray[1];
}
For All Parameter Value use following Code,
$(window).load(function(){
queryString();
});
function queryString()
{
var queryString = window.location.search;
var varArray = queryString.split("&");
for (var i=0;i<varArray.length;i++) {
var param = varArray[i].split("=");
//parameter-value pair
}
}
Here I am posting one example. But it's in jQuery. Hope it will help others:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>
<!-- URL: www.example.com/correct/?message=done&year=1990-->
<script type="text/javascript">
$(function(){
$.url.attr('protocol') // --> Protocol: "http"
$.url.attr('path') // --> host: "www.example.com"
$.url.attr('query') // --> path: "/correct/"
$.url.attr('message') // --> query: "done"
$.url.attr('year') // --> query: "1990"
});
</script>
I had the need to read a URL GET variable and complete an action based on the url parameter. I searched high and low for a solution and came across this little piece of code. It basically reads the current page url, perform some regular expression on the URL then saves the url parameters in an associative array, which we can easily access.
So as an example if we had the following url with the javascript at the bottom in place.
http://TestServer/Pages/NewsArchive.aspx?year=2013&Month=July
All we’d need to do to get the parameters id and page are to call this:
The Code will be:
<script type="text/javascript">
var first = getUrlVars()["year"];
var second = getUrlVars()["Month"];
alert(first);
alert(second);
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
// Usage for URL: http://my.site.com/location?locationId=53cc272c0364aefcb78756cd&shared=false
var id = getUrlVars()["locationId"];
Got from here: http://jquery-howto.blogspot.ru/2009/09/get-url-parameters-values-with-jquery.html
Simple way
function getParams(url){
var regex = /[?&]([^=#]+)=([^&#]*)/g,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
return params;
}
then call it like getParams(url)
Elegant, functional style solution
Let's create an object containing URL param names as keys, then we can easily extract the parameter by its name:
// URL: https://example.com/?test=true&orderId=9381
// Build an object containing key-value pairs
export const queryStringParams = window.location.search
.split('?')[1]
.split('&')
.map(keyValue => keyValue.split('='))
.reduce<QueryStringParams>((params, [key, value]) => {
params[key] = value;
return params;
}, {});
type QueryStringParams = {
[key: string]: string;
};
// Return URL parameter called "orderId"
return queryStringParams.orderId;
It's the N++ time I am looking for a clean way to do this.
Will save this here in case I get back cause I know I will... 🙄
const parseUrlQuery = (value) => {
var urlParams = new URL(value).searchParams
return Array.from(urlParams.keys()).reduce((acc, key) => {
acc[key] = urlParams.getAll(key)
return acc
}, {})
}
console.log(parseUrlQuery('http://url/path?param1=A&param1=B&param2=ABC&param3=61569'))
Here is what I do:
var uriParams = getSearchParameters();
alert(uriParams.c);
// background functions:
// Get object/associative array of URL parameters
function getSearchParameters () {
var prmstr = window.location.search.substr(1);
return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}
// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
var params = {},
prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
// http:localhost:8080/path?param_1=a&param_2=b
var getParamsMap = function () {
var params = window.location.search.split("&");
var paramsMap = {};
params.forEach(function (p) {
var v = p.split("=");
paramsMap[v[0]]=decodeURIComponent(v[1]);
});
return paramsMap;
};
// -----------------------
console.log(getParamsMap()["param_1"]); // should log "a"

How to get "GET" request parameters in JavaScript? [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 1 year ago.
How to get "GET" variables from request in JavaScript?
Does jQuery or YUI! have this feature built-in?
Update June 2021:
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).
Original:
All data is available under
window.location.search
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.
get('foo');
this function will return the variables value or undefined if variable has no value or doesn't exist
You could use jquery.url I did like this:
var xyz = jQuery.url.param("param_in_url");
Check the source code
Updated Source: https://github.com/allmarkedup/jQuery-URL-Parser
try the below code, it will help you get the GET parameters from url .
for more details.
var url_string = window.location.href; // www.test.com?filename=test
var url = new URL(url_string);
var paramValue = url.searchParams.get("filename");
alert(paramValue)
Just to put my two cents in, if you wanted an object containing all the requests
function getRequests() {
var s1 = location.search.substring(1, location.search.length).split('&'),
r = {}, s2, i;
for (i = 0; i < s1.length; i += 1) {
s2 = s1[i].split('=');
r[decodeURIComponent(s2[0]).toLowerCase()] = decodeURIComponent(s2[1]);
}
return r;
};
var QueryString = getRequests();
//if url === "index.html?test1=t1&test2=t2&test3=t3"
console.log(QueryString["test1"]); //logs t1
console.log(QueryString["test2"]); //logs t2
console.log(QueryString["test3"]); //logs t3
Note, the key for each get param is set to lower case. So, I made a helper function. So now it's case-insensitive.
function Request(name){
return QueryString[name.toLowerCase()];
}
Unlike other answers, the UrlSearchParams object can avoid using Regexes or other string manipulation and is available is most modern browsers:
var queryString = location.search
let params = new URLSearchParams(queryString)
// example of retrieving 'id' parameter
let id = parseInt(params.get("id"))
console.log(id)
You can use the URL to acquire the GET variables. In particular, window.location.search gives everything after (and including) the '?'. You can read more about window.location here.
A map-reduce solution:
var urlParams = location.search.split(/[?&]/).slice(1).map(function(paramPair) {
return paramPair.split(/=(.+)?/).slice(0, 2);
}).reduce(function (obj, pairArray) {
obj[pairArray[0]] = pairArray[1];
return obj;
}, {});
Usage:
For url: http://example.com?one=1&two=2
console.log(urlParams.one) // 1
console.log(urlParams.two) // 2
Today I needed to get the page's request parameters into a associative array so I put together the following, with a little help from my friends. It also handles parameters without an = as true.
With an example:
// URL: http://www.example.com/test.php?abc=123&def&xyz=&something%20else
var _GET = (function() {
var _get = {};
var re = /[?&]([^=&]+)(=?)([^&]*)/g;
while (m = re.exec(location.search))
_get[decodeURIComponent(m[1])] = (m[2] == '=' ? decodeURIComponent(m[3]) : true);
return _get;
})();
console.log(_GET);
> Object {abc: "123", def: true, xyz: "", something else: true}
console.log(_GET['something else']);
> true
console.log(_GET.abc);
> 123
You can parse the URL of the current page to obtain the GET parameters. The URL can be found by using location.href.
If you already use jquery there is a jquery plugin that handles this:
http://plugins.jquery.com/project/query-object
The function here returns the parameter by name. With tiny changes you will be able to return base url, parameter or anchor.
function getUrlParameter(name) {
var urlOld = window.location.href.split('?');
urlOld[1] = urlOld[1] || '';
var urlBase = urlOld[0];
var urlQuery = urlOld[1].split('#');
urlQuery[1] = urlQuery[1] || '';
var parametersString = urlQuery[0].split('&');
if (parametersString.length === 1 && parametersString[0] === '') {
parametersString = [];
}
// console.log(parametersString);
var anchor = urlQuery[1] || '';
var urlParameters = {};
jQuery.each(parametersString, function (idx, parameterString) {
paramName = parameterString.split('=')[0];
paramValue = parameterString.split('=')[1];
urlParameters[paramName] = paramValue;
});
return urlParameters[name];
}
Works for me in
url: http://localhost:8080/#/?access_token=111
function get(name){
const parts = window.location.href.split('?');
if (parts.length > 1) {
name = encodeURIComponent(name);
const params = parts[1].split('&');
const found = params.filter(el => (el.split('=')[0] === name) && el);
if (found.length) return decodeURIComponent(found[0].split('=')[1]);
}
}

Get the values from the "GET" parameters (JavaScript) [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 1 year ago.
I have a URL with some GET parameters as follows:
www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
I need to get the whole value of c. I tried to read the URL, but I got only m2. How do I do this using 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);
For older browsers (including Internet Explorer), you can use this polyfill.
You could also use one for URLSearchParams and extract the query string to pass to it with window.location.search.substring(1).
You could also use the code from the original version of this answer that predates URL. The above polyfill is robust and well tested and I strongly recommend it over this though.
You could access location.search, which would give you from the ? character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.
Then you can parse it with this:
function parse_query_string(query) {
var vars = query.split("&");
var query_string = {};
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
var key = decodeURIComponent(pair.shift());
var value = decodeURIComponent(pair.join("="));
// If first entry with this name
if (typeof query_string[key] === "undefined") {
query_string[key] = value;
// If second entry with this name
} else if (typeof query_string[key] === "string") {
var arr = [query_string[key], value];
query_string[key] = arr;
// If third or later entry with this name
} else {
query_string[key].push(value);
}
}
return query_string;
}
var query_string = "a=1&b=3&c=m2-m3-m4-m5";
var parsed_qs = parse_query_string(query_string);
console.log(parsed_qs.c);
You can get the query string from the URL of the current page with:
var query = window.location.search.substring(1);
var qs = parse_query_string(query);
Most implementations I've seen miss out URL-decoding the names and the values.
Here's a general utility function that also does proper URL-decoding:
function getQueryParams(qs) {
qs = qs.split('+').join(' ');
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
//var query = getQueryParams(document.location.search);
//alert(query.foo);
source
function gup( name, url ) {
if (!url) url = location.href;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
return results == null ? null : results[1];
}
gup('q', 'hxxp://example.com/?q=abc')
This is an easy way to check just one parameter:
Example URL:
http://myserver/action?myParam=2
Example Javascript:
var myParam = location.search.split('myParam=')[1]
if "myParam" exists in the URL... variable myParam will contain "2", otherwise it will be undefined.
Maybe you want a default value, in that case:
var myParam = location.search.split('myParam=')[1] ? location.search.split('myParam=')[1] : 'myDefaultValue';
Update: This works better:
var url = "http://www.example.com/index.php?myParam=384&login=admin"; // or window.location.href for current url
var captured = /myParam=([^&]+)/.exec(url)[1]; // Value is in [1] ('384' in our case)
var result = captured ? captured : 'myDefaultValue';
And it works right even when URL is full of parameters.
Browsers vendors have implemented a native way to do this via URL and URLSearchParams.
let url = new URL('http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5');
let searchParams = new URLSearchParams(url.search);
console.log(searchParams.get('c')); // outputs "m2-m3-m4-m5"
Currently supported in Firefox, Opera, Safari, Chrome and Edge. For a list of browser support see here.
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
https://developer.mozilla.org/en-US/docs/Web/API/URL/URL
https://url.spec.whatwg.org/
Eric Bidelman, an engineer at Google, recommends using this polyfill for unsupported browsers.
I found this ages ago, very easy:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
Then call it like this:
var fType = getUrlVars()["type"];
You can get the query string in location.search, then you can split everything after the question mark:
var params = {};
if (location.search) {
var parts = location.search.substring(1).split('&');
for (var i = 0; i < parts.length; i++) {
var nv = parts[i].split('=');
if (!nv[0]) continue;
params[nv[0]] = nv[1] || true;
}
}
// Now you can get the parameters you want like so:
var abc = params.abc;
A super simple way using URLSearchParams.
function getParam(param){
return new URLSearchParams(window.location.search).get(param);
}
It's currently supported in Chrome, Firefox, Safari, Edge, and others.
I wrote a more simple and elegant solution.
var arr = document.URL.match(/room=([0-9]+)/)
var room = arr[1];
Here is a recursive solution that has no regex, and has minimal mutation (only the params object is mutated, which I believe is unavoidable in JS).
It's awesome because it:
Is recursive
Handles multiple parameters of the same name
Deals well with malformed parameter strings (missing values, so on)
Doesn't break if '=' is in the value
Performs URL decoding
And lastly, It's awesome because it...argh!!!
Code:
var get_params = function(search_string) {
var parse = function(params, pairs) {
var pair = pairs[0];
var parts = pair.split('=');
var key = decodeURIComponent(parts[0]);
var value = decodeURIComponent(parts.slice(1).join('='));
// Handle multiple parameters of the same name
if (typeof params[key] === "undefined") {
params[key] = value;
} else {
params[key] = [].concat(params[key], value);
}
return pairs.length == 1 ? params : parse(params, pairs.slice(1))
}
// Get rid of leading ?
return search_string.length == 0 ? {} : parse({}, search_string.substr(1).split('&'));
}
var params = get_params(location.search);
// Finally, to get the param you want
params['c'];
I made a function that does this:
var getUrlParams = function (url) {
var params = {};
(url + '?').split('?')[1].split('&').forEach(function (pair) {
pair = (pair + '=').split('=').map(decodeURIComponent);
if (pair[0].length) {
params[pair[0]] = pair[1];
}
});
return params;
};
Update 5/26/2017, here is an ES7 implementation (runs with babel preset stage 0, 1, 2, or 3):
const getUrlParams = url => `${url}?`.split('?')[1]
.split('&').reduce((params, pair) =>
((key, val) => key ? {...params, [key]: val} : params)
(...`${pair}=`.split('=').map(decodeURIComponent)), {});
Some tests:
console.log(getUrlParams('https://google.com/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('https://google.com/')); // Will log {}
console.log(getUrlParams('a=1&b=2&c')); // Will log {}
Update 3/26/2018, here is a Typescript implementation:
const getUrlParams = (search: string) => `${search}?`
.split('?')[1]
.split('&')
.reduce(
(params: object, pair: string) => {
const [key, value] = `${pair}=`
.split('=')
.map(decodeURIComponent)
return key.length > 0 ? { ...params, [key]: value } : params
},
{}
)
Update 2/13/2019, here is an updated TypeScript implementation that works with TypeScript 3.
interface IParams { [key: string]: string }
const paramReducer = (params: IParams, pair: string): IParams => {
const [key, value] = `${pair}=`.split('=').map(decodeURIComponent)
return key.length > 0 ? { ...params, [key]: value } : params
}
const getUrlParams = (search: string): IParams =>
`${search}?`.split('?')[1].split('&').reduce<IParams>(paramReducer, {})
See this
function getURLParameters(paramName)
{
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i<arrURLParams.length; i++)
{
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i=0; i<arrURLParams.length; i++)
{
if (arrParamNames[i] == paramName)
{
//alert("Parameter:" + arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
The shortest way:
new URL(location.href).searchParams.get("my_key");
ECMAScript 6 solution:
var params = window.location.search
.substring(1)
.split("&")
.map(v => v.split("="))
.reduce((map, [key, value]) => map.set(key, decodeURIComponent(value)), new Map())
I use the parseUri library. It allows you to do exactly what you are asking for:
var uri = 'www.test.com/t.html&a=1&b=3&c=m2-m3-m4-m5';
var c = uri.queryKey['c'];
// c = 'm2-m3-m4-m5'
I use
function getVal(str) {
var v = window.location.search.match(new RegExp('(?:[\?\&]'+str+'=)([^&]+)'));
return v ? v[1] : null;
}
this question has too many answers, so i'm adding another one.
/**
* parses and returns URI query parameters
*
* #param {string} param parm
* #param {bool?} asArray if true, returns an array instead of a scalar
* #returns {Object|Array}
*/
function getURIParameter(param, asArray) {
return document.location.search.substring(1).split('&').reduce(function(p,c) {
var parts = c.split('=', 2).map(function(param) { return decodeURIComponent(param); });
if(parts.length == 0 || parts[0] != param) return (p instanceof Array) && !asArray ? null : p;
return asArray ? p.concat(parts.concat(true)[1]) : parts.concat(true)[1];
}, []);
}
usage:
getURIParameter("id") // returns the last id or null if not present
getURIParameter("id", true) // returns an array of all ids
this copes with empty parameters (those keys present without "=value"), exposure of both a scalar and array-based value retrieval API, as well as proper URI component decoding.
Here is my solution. As advised by Andy E while answering this question, it's not good for your script's performance if it's repeatedly building various regex strings, running loops etc just to get a single value. So, I've come up with a simpler script that returns all the GET parameters in a single object. You should call it just once, assign the result to a variable and then, at any point in the future, get any value you want from that variable using the appropriate key. Note that it also takes care of URI decoding (i.e things like %20) and replaces + with a space:
function getUrlQueryParams(url) {
var queryString = url.split("?")[1];
var keyValuePairs = queryString.split("&");
var keyValue = [];
var queryParams = {};
keyValuePairs.forEach(function(pair) {
keyValue = pair.split("=");
queryParams[keyValue[0]] = decodeURIComponent(keyValue[1]).replace(/\+/g, " ");
});
return queryParams;
}
So, here are are a few tests of the script for you to see:
// Query parameters with strings only, no special characters.
var currentParams = getUrlQueryParams("example.com/foo?number=zero");
alert(currentParams["number"]); // Gives "zero".
// For the URL you stated above...
var someParams = getUrlQueryParams("www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 ");
alert(someParams["c"]); // Gives "m2-m3-m4-m5".
// For a query params with URI encoding...
var someParams = getUrlQueryParams("www.example.com/t.html?phrase=a%20long%20shot&location=Silicon+Valley%2C+USA");
alert(someParams["phrase"]); // Gives "a long shot".
alert(someParams["location"]); // Gives "Silicon Valley, USA".
The easiest way using the replace() method:
From the urlStr string:
paramVal = urlStr.replace(/.*param_name=([^&]*).*|(.*)/, '$1');
or from the current URL:
paramVal = document.URL.replace(/.*param_name=([^&]*).*|(.*)/, '$1');
Explanation:
document.URL - interface returns the document location (page url) as a string.
replace() - method returns a new string with some or all matches of a pattern replaced by a replacement.
/.*param_name=([^&]*).*/ - the regular expression pattern enclosed between slashes which means:
.* - zero or more of any characters,
param_name= - param name which is serched,
() - group in regular expression,
[^&]* - one or more of any characters excluding &,
| - alternation,
$1 - reference to first group in regular expression.
var urlStr = 'www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5';
var c = urlStr.replace(/.*c=([^&]*).*|(.*)/, '$1');
var notExisted = urlStr.replace(/.*not_existed=([^&]*).*|(.*)/, '$1');
console.log(`c === '${c}'`);
console.log(`notExisted === '${notExisted}'`);
Yet another suggestion.
There are some good answers already, but I found them needlessly complex and hard to understand. This is short, simple, and returns a simple associative array with key names corresponding to the token names in the URL.
I added a version with comments below for those who want to learn.
Note this relies on jQuery ($.each) for its loop, which I recommend instead of forEach. I find it simpler to ensure cross-browser compatibility using jQuery across the board rather than plugging in individual fixes to support whichever new functions aren't supported in older browsers.
Edit: After I wrote this I noticed Eric Elliott's answer, which is almost the same, though it uses forEach, while I'm generally against (for reasons stated above).
function getTokens(){
var tokens = [];
var query = location.search;
query = query.slice(1);
query = query.split('&');
$.each(query, function(i,value){
var token = value.split('=');
var key = decodeURIComponent(token[0]);
var data = decodeURIComponent(token[1]);
tokens[key] = data;
});
return tokens;
}
Commented version:
function getTokens(){
var tokens = []; // new array to hold result
var query = location.search; // everything from the '?' onward
query = query.slice(1); // remove the first character, which will be the '?'
query = query.split('&'); // split via each '&', leaving us an array of something=something strings
// iterate through each something=something string
$.each(query, function(i,value){
// split the something=something string via '=', creating an array containing the token name and data
var token = value.split('=');
// assign the first array element (the token name) to the 'key' variable
var key = decodeURIComponent(token[0]);
// assign the second array element (the token data) to the 'data' variable
var data = decodeURIComponent(token[1]);
tokens[key] = data; // add an associative key/data pair to our result array, with key names being the URI token names
});
return tokens; // return the array
}
For the examples below we'll assume this address:
http://www.example.com/page.htm?id=4&name=murray
You can assign the URL tokens to your own variable:
var tokens = getTokens();
Then refer to each URL token by name like this:
document.write( tokens['id'] );
This would print "4".
You can also simply refer to a a token name from the function directly:
document.write( getTokens()['name'] );
...which would print "murray".
Or if you don't want to reinvent the URI parsing wheel use URI.js
To get the value of a parameter named foo:
new URI((''+document.location)).search(true).foo
What that does is
Convert document.location to a string (it's an object)
Feed that string to URI.js's URI class construtor
Invoke the search() function to get the search (query) portion of the url
(passing true tells it to output an object)
Access the foo property on the resulting object to get the value
Here's a fiddle for this.... http://jsfiddle.net/m6tett01/12/
For Single Parameter Value like this index.html?msg=1 use following code,
$(window).load(function(){
queryString();
});
function queryString()
{
var queryString = window.location.search.substring(1);
var varArray = queryString.split("="); //eg. index.html?msg=1
var param1 = varArray[0];
var param2 = varArray[1];
}
For All Parameter Value use following Code,
$(window).load(function(){
queryString();
});
function queryString()
{
var queryString = window.location.search;
var varArray = queryString.split("&");
for (var i=0;i<varArray.length;i++) {
var param = varArray[i].split("=");
//parameter-value pair
}
}
Here I am posting one example. But it's in jQuery. Hope it will help others:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>
<!-- URL: www.example.com/correct/?message=done&year=1990-->
<script type="text/javascript">
$(function(){
$.url.attr('protocol') // --> Protocol: "http"
$.url.attr('path') // --> host: "www.example.com"
$.url.attr('query') // --> path: "/correct/"
$.url.attr('message') // --> query: "done"
$.url.attr('year') // --> query: "1990"
});
</script>
I had the need to read a URL GET variable and complete an action based on the url parameter. I searched high and low for a solution and came across this little piece of code. It basically reads the current page url, perform some regular expression on the URL then saves the url parameters in an associative array, which we can easily access.
So as an example if we had the following url with the javascript at the bottom in place.
http://TestServer/Pages/NewsArchive.aspx?year=2013&Month=July
All we’d need to do to get the parameters id and page are to call this:
The Code will be:
<script type="text/javascript">
var first = getUrlVars()["year"];
var second = getUrlVars()["Month"];
alert(first);
alert(second);
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
// Usage for URL: http://my.site.com/location?locationId=53cc272c0364aefcb78756cd&shared=false
var id = getUrlVars()["locationId"];
Got from here: http://jquery-howto.blogspot.ru/2009/09/get-url-parameters-values-with-jquery.html
Simple way
function getParams(url){
var regex = /[?&]([^=#]+)=([^&#]*)/g,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
return params;
}
then call it like getParams(url)
Elegant, functional style solution
Let's create an object containing URL param names as keys, then we can easily extract the parameter by its name:
// URL: https://example.com/?test=true&orderId=9381
// Build an object containing key-value pairs
export const queryStringParams = window.location.search
.split('?')[1]
.split('&')
.map(keyValue => keyValue.split('='))
.reduce<QueryStringParams>((params, [key, value]) => {
params[key] = value;
return params;
}, {});
type QueryStringParams = {
[key: string]: string;
};
// Return URL parameter called "orderId"
return queryStringParams.orderId;
It's the N++ time I am looking for a clean way to do this.
Will save this here in case I get back cause I know I will... 🙄
const parseUrlQuery = (value) => {
var urlParams = new URL(value).searchParams
return Array.from(urlParams.keys()).reduce((acc, key) => {
acc[key] = urlParams.getAll(key)
return acc
}, {})
}
console.log(parseUrlQuery('http://url/path?param1=A&param1=B&param2=ABC&param3=61569'))
Here is what I do:
var uriParams = getSearchParameters();
alert(uriParams.c);
// background functions:
// Get object/associative array of URL parameters
function getSearchParameters () {
var prmstr = window.location.search.substr(1);
return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}
// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
var params = {},
prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
// http:localhost:8080/path?param_1=a&param_2=b
var getParamsMap = function () {
var params = window.location.search.split("&");
var paramsMap = {};
params.forEach(function (p) {
var v = p.split("=");
paramsMap[v[0]]=decodeURIComponent(v[1]);
});
return paramsMap;
};
// -----------------------
console.log(getParamsMap()["param_1"]); // should log "a"

how to get GET and POST variables with JQuery?

How do I simply get GET and POST values with JQuery?
What I want to do is something like this:
$('#container-1 > ul').tabs().tabs('select', $_GET('selectedTabIndex'));
For GET parameters, you can grab them from document.location.search:
var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
$_GET[decode(arguments[1])] = decode(arguments[2]);
});
document.write($_GET["test"]);
For POST parameters, you can serialize the $_POST object in JSON format into a <script> tag:
<script type="text/javascript">
var $_POST = <?php echo json_encode($_POST); ?>;
document.write($_POST["test"]);
</script>
While you're at it (doing things on server side), you might collect the GET parameters on PHP as well:
var $_GET = <?php echo json_encode($_GET); ?>;
Note: You'll need PHP version 5 or higher to use the built-in json_encode function.
Update: Here's a more generic implementation:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
var $_GET = getQueryParams(document.location.search);
There's a plugin for jQuery to get GET params called .getUrlParams
For POST the only solution is echoing the POST into a javascript variable using PHP, like Moran suggested.
Or you can use this one http://plugins.jquery.com/project/parseQuery, it's smaller than most (minified 449 bytes), returns an object representing name-value pairs.
why not use good old PHP? for example, let us say we receive a GET parameter 'target':
function getTarget() {
var targetParam = "<?php echo $_GET['target']; ?>";
//alert(targetParam);
}
Keep it simple
replace VARIABLE_KEY with the key of the variable to get its value
var get_value = window.location.href.match(/(?<=VARIABLE_KEY=)(.*?)[^&]+/)[0];
With any server-side language, you will have to emit the POST variables into javascript.
.NET
var my_post_variable = '<%= Request("post_variable") %>';
Just be careful of empty values. If the variable you attempt to emit is actually empty, you will get a javascript syntax error. If you know it's a string, you should wrap it in quotes. If it's an integer, you may want to test to see if it actually exists before writing the line to javascript.
You can try Query String Object plugin for jQuery.
Here's something to gather all the GET variables in a global object, a routine optimized over several years. Since the rise of jQuery, it now seems appropriate to store them in jQuery itself, am checking with John on a potential core implementation.
jQuery.extend({
'Q' : window.location.search.length <= 1 ? {}
: function(a){
var i = a.length,
r = /%25/g, // Ensure '%' is properly represented
h = {}; // (Safari auto-encodes '%', Firefox 1.5 does not)
while(i--) {
var p = a[i].split('=');
h[ p[0] ] = r.test( p[1] ) ? decodeURIComponent( p[1] ) : p[1];
}
return h;
}(window.location.search.substr(1).split('&'))
});
Example usage:
switch ($.Q.event) {
case 'new' :
// http://www.site.com/?event=new
$('#NewItemButton').trigger('click');
break;
default :
}
Hope this helps. ;)
jQuery plugins seem nice but what I needed is a quick js function to parse the get params.
Here is what I have found.
http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
If your $_GET is multidimensional, this might be what you're wanting:
var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
//handling for multidimensional arrays
if(decode(arguments[1]).indexOf("[]") > 0){
var newName = decode(arguments[1]).substring(0, decode(arguments[1]).length - 2);
if(typeof $_GET[newName] == 'undefined'){
$_GET[newName] = new Array();
}
$_GET[newName].push(decode(arguments[2]));
}else{
$_GET[decode(arguments[1])] = decode(arguments[2]);
}
});
simple, but yet usefull to get vars/values from URL:
function getUrlVars() {
var vars = [], hash, hashes = null;
if (window.location.href.indexOf("?") && window.location.href.indexOf("&")) {
hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
} else if (window.location.href.indexOf("?")) {
hashes = window.location.href.slice(window.location.href.indexOf('?') + 1);
}
if (hashes != null) {
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars[hash[0]] = hash[1];
}
}
return vars;
}
I found it somewhere on the internet, just fixed few bugs
Use following function:
var splitUrl = function() {
var vars = [], hash;
var url = document.URL.split('?')[0];
var p = document.URL.split('?')[1];
if(p != undefined){
p = p.split('&');
for(var i = 0; i < p.length; i++){
hash = p[i].split('=');
vars.push(hash[1]);
vars[hash[0]] = hash[1];
}
}
vars['url'] = url;
return vars;
};
and access variables as vars['index'] where 'index' is name of the get variable.
My approach:
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
Just for the record, I wanted to know the answer to this question, so I used a PHP method:
<script>
var jGets = new Array ();
<?
if(isset($_GET)) {
foreach($_GET as $key => $val)
echo "jGets[\"$key\"]=\"$val\";\n";
}
?>
</script>
That way all my javascript/jquery that runs after this can access everything in the jGets. Its an nice elegant solution I feel.

Categories