How to get the value from the GET parameters?

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?

Text Copied From stackoverflow.com
on : Thu, Jun 11, 2009 Views : 1383058

Accepted Answer

JavaScript itself has nothing built in for handling query string parameters.

In a (modern) browser you can use the (experimental at time of writing) URL object;

var url_string = http:
//www.example.com/t.html?a=1&
b=3&
c=m2-m3-m4-m5;
 
//window.location.href var url = new URL(url_string);
 var c = url.searchParams.get(c);
 console.log(c);


For older browsers, you can use this polyfill or the code from the original version of this answer that predates URL:

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

  
// If first entry with this name
  if (typeof query_string[pair[0]] === undefined) 
{

    query_string[pair[0]] = decodeURIComponent(pair[1]);

    
// If second entry with this name
  
} else if (typeof query_string[pair[0]] === string) 
{

    var arr = [query_string[pair[0]], decodeURIComponent(pair[1])];

    query_string[pair[0]] = arr;

    
// If third or later entry with this name
  
} else 
{

    query_string[pair[0]].push(decodeURIComponent(pair[1]));

  
}   
}   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);
 
Text Copied From stackoverflow.com
on : Thu, Jun 11, 2009

Ask Question

If you want to ask question you must LogIn or SignUp
Login SignUp

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp