Checking GET variables in the URL with JS/jQuery? [duplicate] - javascript

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 9 years ago.
If I have a url https://stackoverflow.com/?variable=12345 how can I check if there is a GET parameter in the URL and what it is equals to in JS or jQuery?
For example in PHP:
if(isset($_GET['variable']))
$variable = $_GET['variable'];
Thanks.

function get_var(var_name){
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == var_name){return pair[1];}
}
return(false);
}
And to use:
var get_variable = get_var("variable");
if (get_variable !== '') {
// Variable exists
}

Related

how to get value from href in javascript [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Get the values from the "GET" parameters (JavaScript) [duplicate]
(63 answers)
Closed 4 years ago.
I have the following url of my html page, and I am looking for a way to get the value "1997" passed into a string using javascript.
I am thinking of using Regex, but isn't there a much simpler way?
http://localhost:8080/App/sample?proj=1997
Here is a quick function using split and a for loop.
function getParam (url, param) {
try {
/* Get the parameters. */
var params = url.split("?")[1].split("&");
/* Iterate over each parameter. */
for (var i = 0, l = params.length; i < l; i++) {
/* Split the string to a key-value pair */
var pair = params[i].split("=");
/* Check whether the param given matches the one iterated. */
if (pair[0] == param) return pair[1];
}
} catch (e) {}
/* Return null, if there is no match. */
return null;
}
/* Example. */
console.log(
getParam("http://localhost/dir/file", "proj"),
getParam("http://localhost:8080/App/sample?proj=1997", "proj")
);

Unserialize a request string to an array [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 5 years ago.
In Javascript, if you serialize() a key/value array pair, then you'll get something like single=Single&multiple=Multiple. Is there any way to "unserialize" this string to get an array of key/value pairs again? If not, what's the most efficient way?
As answered here: https://stackoverflow.com/a/10126995/183181
var str = 'single=Single&multiple=Multiple';
console.log( getParams(str) );
function getParams (str) {
var queryString = str || window.location.search || '';
var keyValPairs = [];
var params = {};
queryString = queryString.replace(/.*?\?/,"");
if (queryString.length)
{
keyValPairs = queryString.split('&');
for (pairNum in keyValPairs)
{
var key = keyValPairs[pairNum].split('=')[0];
if (!key.length) continue;
if (typeof params[key] === 'undefined')
params[key] = [];
params[key].push(keyValPairs[pairNum].split('=')[1]);
}
}
return params;
}

Why this code doesn't work? (Variable objects key and value) [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 6 years ago.
var elems = [];
var at1 = $(indx).attr('class'); //or any string
var at2 = $(indx).html(); //or any string
elems.push({
at1: at2
});
The output I get is:
this
Why can not I set the key as a string?
The way you create an object, the key is going to be interpreted literally as "at1" string. In your case you need to do it slightly more verbose:
var at1 = $(indx).attr('class');
var at2 = $(indx).html();
var obj = {};
obj[at1] = at2;
elems.push(obj);
... or using ES2015 computed property name:
var at1 = $(indx).attr('class');
var at2 = $(indx).html();
elems.push({
[at1]: at2
});

Assigning an object property as the key of a new property in Javascript [duplicate]

This question already has answers here:
Passing in dynamic key:value pairs to an object literal? [duplicate]
(3 answers)
Closed 8 years ago.
What I am trying to do is take two properties of a single Javascript object, and creat a new array with the first property as a key for the second one.
var optionArray = {}
for (var i = 0; i < this.collection.models.length; i++) {
var f = $('.optionChange:eq('+i+')')[0].value;
if (f === "yes") {
this.collection.models[i].set({"optionValue":"yes"});
}
else{
this.collection.models[i].set({"optionValue":"no"});
}
var option1 = this.collection.models[i].get("optionName");
var option2 = this.collection.models[i].get("optionValue");
var result = option1 + ":" + option2;
optionArray[i] = {
option1 : option2
}
};
console.log(optionArray);
This however only outputs to {option1:"option2 property value"}. The key will not change, it only displays as the word option1. Is there any way to accomplish this?
This is wrong, since you can't use a variable as the property name when you use {} notation:
optionArray[i] = {
option1 : option2
}
Try this instead:
optionArray[i] = {} // Make a new empty object
optionArray[i][option1] = option2;
You have to write it like this:
optionArray[i] = {}
optionArray[i][option1] = option2;

Get querystring array values in Javascript [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 9 years ago.
I have a form that uses the get method and contains an array:
http://www.example.com?name[]=hello&name[]=world
I'm trying to retrieve array values 'hello' and 'world' using JavaScript or jQuery.
I've had a look at similar solutions on Stack Overflow (e.g. How can I get query string values in JavaScript?) but they seem to only deal with parameters rather than arrays.
Is it possible to get array values?
There you go: http://jsfiddle.net/mm6Bt/1/
function getURLParam(key,target){
var values = [];
if (!target) target = location.href;
key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var pattern = key + '=([^&#]+)';
var o_reg = new RegExp(pattern,'ig');
while (true){
var matches = o_reg.exec(target);
if (matches && matches[1]){
values.push(matches[1]);
} else {
break;
}
}
if (!values.length){
return null;
} else {
return values.length == 1 ? values[0] : values;
}
}
var str = 'http://www.example.com?name[]=hello&name[]=world&var1=stam';
console.log(getURLParam('name[]',str));
console.log(getURLParam('var1',str));

Categories

Resources