How to parse the Query parameters in Javascript

Not applicable

Hello All,

I have a string like "https://www.google.com/abc/xyz?firstQp=5&secondQp=IamMaster".

I am looking for the best possible and optimised piece of javascript code to extract firstQp and secondQp into context variables.

Can anyone quickly help me here ?

0 4 6,432
4 REPLIES 4

Hi @Meghdeep Basu,

Do you want to extract the query parameters from a string or is that a API request URL?

If it is a request URL then query parameters are already available in context object as variables.

if(request.queryParams['firstQp']){
	print(context.proxyRequest.queryParams['firstQp'][0] );  // 5	
        print(context.proxyRequest.queryParams['firstQp'][1] ); // IamMaster	
}

Check documentation for Javascript Object model for details.

Other wise if you want to parse the url string into individual components such a host,path, hash etc you can use a simple JS function

function getLocation(href) {
    var location = document.createElement("a");
    location.href = href;
    if (location.host == "") {
      location.href = location.href;
    }
    return location;
};

var url = getLocation("http://google.com/abc?param1=123&param2=abc");
//above function will return an object with href properties
url.host // google.com
url.search // ?param1=123&param2=abc
url.protocol // http

if you want to extract the query parameters from string then use the method as described in this blog :

https://www.sitepoint.com/get-url-parameters-with-javascript/

Cheers!!

No. my requirement was to use it in a javascript. Its not part of request query parameters.:) Please check the solution that I designed below to meet this requirement.

Not applicable

I got the answer:

var String = "https://www.google.com/abc/xyz?firstQp=5&firstQp=IamMaster"; 
var firstQp = "";
var secondQp = "";

var mainString = String.split("?");
var queryparams = mainString[1].split("&");

for (i = 0; i<2; i++) {

	var queryparam = queryparams[i].split("=");

	if (queryparam[0].indexOf("firstQp") != -1)
firstQp = queryparam[1]; if (queryparam[0].indexOf("secondQp") != -1) secondQp = queryparam[1]; }

URL parsing can be a beast. If your URLs are always very consistent like above, rolling your own isn't so bad. If that url string might vary a bit, I recommend looking at URI.js (https://medialize.github.io/URI.js/). It's easy to include it as a resource for your js scripts and it handles everything I've needed to throw at it.