0%

Hey! Do you have any query related to front end?

Sign in Sign up

Convert query string to jsonBack

Query string in DOM has always been a big problem. Searched a lot but could not found any suitable solution for this. Normally people convert it into keys and pairs format. But in latest browser found that, this can be done by using JSON Object, which is available in modern browser.

Getting started:

First you will have to follow older fashion, that is to convert the query string in to an array by replacing "?" from the string, through slice() function.

location.search.slice(1);

Then you will have to split the Array by passing it the ‘&’ character.

var pairs = location.search.slice(1).split('&');

Now using the array .forEach() function we can go through pairs and split them again, this time we will use "=". By this way we will get index "0" as key and index "1" as value.

And by using decodeURIComponent function we will remove any HTML encoding.

var pairs = location.search.slice(1).split('&');

var result = {};
pairs.forEach(function(pair) {
    pair = pair.split('=');
    result[pair[0]] = decodeURIComponent(pair[1] || '');
});

Last step:

The final step is to use JSON.stringify method to parse the object, and then again call the JSON.parse() function to convert that back to an object.

Final code goes like this:

function QueryToJSON() {            
    var pairs = location.search.slice(1).split('&');
    
    var result = {};
    pairs.forEach(function(pair) {
        pair = pair.split('=');
        result[pair[0]] = decodeURIComponent(pair[1] || '');
    });

    return JSON.parse(JSON.stringify(result));
}

var query_string = QueryToJSON();

How to comment:

  • Create an account in discuss by clicking on login next to arrow.
  • Create password for discuss and varify your email id, through your mail.
  • Refresh page and comment.

You might also like

  • Tabbing with id and rel attribute

    Tabbing functionality with respect to ID and rel attribute.

    • 217
    • 8
    • 217
    • facebook icon
    • twitter icon
    • google plus
  • Load images visible to user after page load

    Load only those image which is visible to visitor

    • 315
    • 8
    • 315
    • facebook icon
    • twitter icon
    • google plus
  • Image selection like checkbox

    Select your image like a checkbox with little jQuery

    • 356
    • 34
    • 356
    • facebook icon
    • twitter icon
    • google plus

Latest quries posted

gopa kumarabout 3 years ago

amit singhabout 3 years ago

rahmat aliabout 3 years ago

mandavi tiwariabout 3 years ago

rahul sharmaabout 3 years ago

Ask question
Latest video
Learn Angular
Profile pic
Guest Back
Username
Password