5

i am trying to create array from window.location.hash variable but i am failling.

My code is:

        $.each(window.location.hash.replace("#", "").split("&"), function (i, value) {
            value = value.split("=");

            var my_item = {value[0] : value[1]};
            form_data[i] = my_item; 
        });
        console.log(form_data);

Thanks.

6
  • 1
    Are you trying to parse the hash or the search? window.location.search returns the part after the ? and before the # which is the part that has the query string key/values. Commented Jul 13, 2010 at 4:17
  • @Andir - I don't think that's the case, because the OP removed the hash sign. Then again, apparently I assumed too much already. Commented Jul 13, 2010 at 4:24
  • I know that some implementations use the hash for things like history and whatnot, but I wanted to eliminate the possibility of a mistaken location identifier. Commented Jul 13, 2010 at 4:27
  • @Kobi +1 I removed hash sign to ready parse. Commented Jul 13, 2010 at 4:44
  • You didn't remove everything before #. The url will get read along, which I think is not what you want. Commented Aug 25, 2010 at 6:39

7 Answers 7

5

Give this a try:

var hash = window.location.hash.slice(1);
var array = hash.split("&");

var values, form_data = {};

for (var i = 0; i < array.length; i += 1) {
    values = array[i].split("=");
    form_data[values[0]] = values[1];
}

console.log(form_data);

...Of course I suspect you may be wanting the search property, rather than hash, but I don't know your specific use case.

Sign up to request clarification or add additional context in comments.

Comments

2
your code is correct only error is

 $.each(window.location.hash.replace("#", "").split("&"), function (i, value) {
            value = value.split("=");
            var _formItem={};
            var my_item={};
            my_item[value[0]]= value[1]; 
            form_data[i] = my_item; 
        });

Comments

2

JavaScript doesn't support the following notation:

var my_item = {value[0] : value[1]};

Try this instead:

var my_item = {};
my_item[value[0]] = value[1];

This will create an array, where each element has a key and a value, for example:

[{name: jason}, {age: 23}, {location: pacific}] //array of single keys

Using a hash probably makes more scene in your case, so you can call form_data['age'], and won't have to look though the array:

initialize form_data to an object:

form_data = {};

Add keys directly to it:

form_data[value[0]] = value[1];

So the result is:

{name: jason, age: 23, location: pacific} //associative array with properties

4 Comments

That won't work either; my_item will be redeclared each time, so it will only contain the last key/value pair.
@no - nope. It is pushed to the form_data array, which is safe to assume defined before the loop.
how is that safe to assume? I assumed it was not declared.
Then it will not work. You must declare form_data as an array first (before the whole $.each loop) before you can use form_data[i] to add in data.
2

To get associative array from url hash:

function readUrlHashParams() {
    var result = {};
    var hashParam = window.location.hash.substring(1);
    var params = hashParam.split("&");

    $.each(params, function (index, set) {
        var paramSet = set.split("=");
        if (typeof (paramSet[1]) !== "undefined") {
            result[paramSet[0]] = decodeURIComponent(paramSet[1]);
        } else {
            result[paramSet[0]] = "";
        }
    });
    return result;
}

Example URL

http://localhost/Index.html#Param1=test1&Param2=Test2&Param3=

Result

var test = readUrlHashParams();
console.log(test);

Object {Param1: "test1", Param2: "Test2", Param3: ""}

Comments

0

Undeclared form_data is not an object, so it can't have any properties, so form_data[i] = ... will fail. Run this script in a decent browser and the console should show you a message amounting to what I just said.

edit - no it won't because the bogus object literal syntax will trip it up first as Kobi mentions. Both issues should be fixed.

Comments

0

Here's a sample based on the following URL:

http://www.someUrl.com/Index.htm#foo=bob&moo=alice

<!DOCTYPE html>
<html lang="en">
<head>
    <title>hash me long time</title>
</head>
<body>

    <p>Hello World!</p>

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">

        $(function () {

            var hash = window.location.hash.replace('#', '').split('&');
            var myArray = new Array();
            for (var x = 0; x < hash.length; x++) {
                var itemArray = hash[x].split('=');
                var item = new Object();
                item.key = itemArray[0];
                item.value = itemArray[1];
                myArray.push(item);
            }

            for (var x = 0; x < myArray.length; x++)
                console.log(myArray[x].key + ' is ' + myArray[x].value);

        });

    </script>
</body>
</html>

5 Comments

Thanks for code but i have to access variables like this: myArray["foo"] it this case i can't.
mTuran: Your original code, had it worked, wouldn't have done that either. form_data, assuming it was declared, would have numeric properties, just like Andrew's myArray. There was no indication that non-numeric properties were a prerequisite. And where is 'foo' supposed to come from anyway?
What is driving this decision to reference values via string index, as in myArray["foo"], is it Professor Smith?
because i have to have access variables individually
Professor Smith from Duke University, or UCB?
0

Perfect Object.

location.hash = location.hash ? location.hash : "#!";
$.each((location.hash ? location.hash.split("#!") : [""])[1].split("&"), (function () {
 y = this.split("=");
 $hash[y[0]] = y[1];
}));

If you are not yet using #! you can change it to #

1 Comment

$hash comes back as undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.