0

Can I put in some variable some Parameter from Query String Parameters?

i.e.

Headers:

General....

Response Headers....

Request Headers....

Query String Parameters: name:john home:london

/page.php?name=john&home=london

I need var nameQuery = john or var homeQuery = london

4 Answers 4

6

There is a much better way to get query params than parsing a string.

Now, an official API called URLSearchParams is available, very easy to use.

var queryString = "?id=1234&action=edit"
var queryParams = new URLSearchParams(queryString);
// p.s. you can get the query string by plain JS like
// var queryString = window.location.search;

console.log(queryParams.has('id')); // true
console.log(queryParams.get('action')); // "edit"
console.log(queryParams.getAll('action')); // ["edit"]
console.log(queryParams.toString()); // "?id=1234&action=edit"
queryParams.append('ref', 'top_page')
console.log(queryParams.toString()); // "?id=1234&action=edit&ref=top_page"

Sign up to request clarification or add additional context in comments.

Comments

3

You can use split() for this liek bellow,

 var url = window.location.href;
 var params = url.split('?')[1].split('&'); 
 for(var i =0;i<params.length;i++){
 	var temp = params[i].split('=');
 	var key   = temp[0];
 	var value = temp[1];
 	console.log(key +':'+value);
 }

Result

   name:john
   home:london

Comments

1

var url = '/page.php?name=john&home=london';
var params = url.split('?')[1].split('&');//get the url params array seperated from url 
var queryObj = {};
for(i = 0; i < params.length; i++){
  pair = params[i].split('='); //spilt to key and value
  queryObj[ pair[0] + 'Query' ] = pair[1];
}
console.log(queryObj)

Comments

0

You can use location.search, which will give you:

"?name=john&home=london"

So, using the above info, you can separate them this way:

search = location.search.substr(1).split("&");

Which you will get:

["name=john", "home=london"]

That you can loop and get the values.

var stuff = {};
for (i = 0; i < search.length; i++) {
  thing = search[i].split("=");
  stuff[thing[0]] = thing[1];
}

And finally, logging stuff you get:

Object {name: "john", home: "london"}

You can use:

stuff.name; // john
stuff.home; // london

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.