HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Get the values from the "GET" parameters (JavaScript)

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
fromthevaluesparametersjavascriptget

Problem

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?

Solution

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



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);

Code Snippets

var query = window.location.search.substring(1);
var qs = parse_query_string(query);

Context

Stack Overflow Q#979975, score: 2711

Revisions (0)

No revisions yet.