Jeffrey04
Jeffrey04

Reputation: 6338

doing substring in window.location.hash

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

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.

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

Upvotes: 2

Views: 7477

Answers (4)

Fabien Ménager
Fabien Ménager

Reputation: 140185

You could also do that :

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

Upvotes: 0

Gumbo
Gumbo

Reputation: 655677

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

Upvotes: 4

annakata
annakata

Reputation: 75862

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;
}

Upvotes: 0

Jeffrey04
Jeffrey04

Reputation: 6338

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;
    };

Upvotes: 1

Related Questions