Can I put in some variable some Parameter from Query String Parameters?
ie
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
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); // ps 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"
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
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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.