Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to convert URL hash parameters into object (key value pairs)

Consider this string: #page?param1=a&param2=b&param3=c

A hybrid application I have been working on uses window.location.hash to route the application to the right page. Often, these URLs contain parameters after the hash. Sure, this isn't standard, but it's a good solution that works nicely for our application.

I need to create a function that will take all of the parameters in the hash and return them in a object, for example: {param: value}.

I have tried other questions solution's that involve window.location.search but sadly that just returns an empty string when the parameters are after a hash.

My attempt looks like this:

return JSON.parse('{"' + decodeURI(window.location.hash).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}');

The solution is taken from another question that uses window.location.search but using window.location.hash doesn't quite work properly, the first parameter (after the question mark) shows as undefined.

How can I create a function that would return hash parameters in an object?

The desired result for the string above would be this:

{ param1: 'a', param2: 'b', param3: 'c' }
like image 200
jskidd3 Avatar asked May 05 '14 21:05

jskidd3


1 Answers

You can use this function:

function parseParms(str) {
    var pieces = str.split("&"), data = {}, i, parts;
    // process each query pair
    for (i = 0; i < pieces.length; i++) {
        parts = pieces[i].split("=");
        if (parts.length < 2) {
            parts.push("");
        }
        data[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
    }
    return data;
}

This is taken from the .parseParms() method of a larger set of functionality on github I wrote for parsing a URL into all its pieces.

Input is a string in the form of:

"aaa=1&bbb=99&name=Bob"

and it will return an object like this:

{aaa: 1, bbb: 99, name: "Bob"}

So, if you have other things in the string besides just the parameters above, then you would need to remove those first before calling this function.

Working demo:

function parseParms(str) {
    var pieces = str.split("&"), data = {}, i, parts;
    // process each query pair
    for (i = 0; i < pieces.length; i++) {
        parts = pieces[i].split("=");
        if (parts.length < 2) {
            parts.push("");
        }
        data[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
    }
    return data;
}

console.log(parseParms("aaa=1&bbb=99&name=Bob"));
like image 70
jfriend00 Avatar answered Oct 01 '22 19:10

jfriend00