Get Query String Value from URL | Query string value in JavaScript

Views:
57

As a JavaScript Developer dynamic things can be done by calling API\’s. But making API\’s almost impossible for UI Developer or need developer help.Most of time we need to do some small tweaks or changes on our HTML DOM based on user selection or behavior. Here we use of our URL, As we all know we can pass small data information in our URL\’s.Parsing and URL\’s in JavaScript itself a tedious task. Here I will describe the easiest way to parse URL.

Location Object

We all know we JavaScript Object called location which contains all information regarding URL content.It has lots of property by using them we can get our desired result. how I am explaining below.Assuming we have URL like below:

http://abc.com/test.html?j=1&k=3&i=9

now to get the protocol of above link we will use

location.protocol  // It will return the protocol you are using for your website like http: or https:

To get the domain name of above link we will use

location.pathname  // It will return the domain name of your website like // result : abc.com

To get the query parameter we will use search property which will return complete query available in your URL with ? which is use to start query string.

location.search // In above case it will return :  ?j=1&k=3&i=9

Use of search not fulfill our requirement as we didn’t get our desired result. As while working on our HTML we probably require the query parameter value here as result we have whole query as a string.to get the value of k we need to write below code.

var x4 = location.search;
var c = x4.replace("?","").split("&");
console.log(c);
for(var i=0; i< c.length; i++){     
	if(c[i].search("k") > -1){        
		console.log(c[i].search("k"),"str.search()",i)        
		var query = c[i].replace("k=", "");        
		console.log("Final Result: "+query)     
	}
}

Your can wrap above JavaScript code into any function.

Note:- Query string must be unique or should not the part of query value, As we using javascript method search which perform search string which also search into its value. 

Easiest way to get Query String

Comments Your Suggestions