2

Somehow window.location.hash is being handled differently in different browsers. If I have a url as follows

http://maps-demo.bytecraft.com.my/postdemo/parcel
    #parcel/history/1?as=json&desc[]=ctime&desc[]=history_id

and I am interested in getting values in between #parcel/history/ and ?as=json ... so the substring statement would be something similar to

window.location.hash.substring(14, window.location.hash.search(/\?/g));

I have that work in firefox 3.0.10 without problem but the same substring statement doesn't work in Opera 9.60.

After some quick searching, I found some interesting info that may help

  • window.location.hash should always return urlencoded string, but this is a bug in Firefox

If the hash part of the URL contains encoded characters (see Core_JavaScript_1.5_Reference:Global_Functions:encodeURIComponent), hash returns the decoded URL part. This is a bug in Firefox. href, search and pathname return the correct, encoded URL parts.

  • Opera returns only #parcel/history/1 and ignores the remaining string, and this is the main reason why my substring statement failed...

Is there a better way if I want to extract the string between #parcel/history/ and ?as=json.... besides regular expression?!

Jeffrey04
  • 5,768
  • 10
  • 41
  • 65

4 Answers4

4

Try this:

var match = window.location.href.match(/^[^#]+#([^?]*)\??(.*)/);
var hashPath = match[1];
var hashQuery = match[2];

This matches the following parts of the hash:

…#parcel/history/1?as=json&desc[]=ctime&desc[]=history_id
  \______________/ \____________________________________/
   hashPath         hashQuery
Gumbo
  • 620,600
  • 104
  • 758
  • 828
1

This is my current solution to the problem

    var get_hash_end = function(_hash) {
        var result = _hash.length;

        if(_hash.search(/\?/g) != -1) {
            result = _hash.search(/\?/g);
        }

        return result;
    };
Jeffrey04
  • 5,768
  • 10
  • 41
  • 65
0

You could just use window.location.href instead of hash but why not use regex? More reliable and future-safe than a method based on substringing from character N. Try:

window.location.href.match(/#parcel\/history\/(.*?)(\?|$)/)[1]

Regex isn't the right answer all the time, but sometimes it's just right.

Edit: cleaned up method encapsulation

function GetValue()
{
    var m = window.location.href.match(/#parcel\/history\/(.*?)(\?|$)/);
    return m ? m[1] : null;
}
annakata
  • 72,622
  • 16
  • 112
  • 180
0

You could also do that :

var whatYouWant = window.location.hash.split('?')[0].substring(14);

Fabien Ménager
  • 139,991
  • 3
  • 39
  • 60