doing substring in [removed].hash

2020-02-29 20:03发布

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?!

标签: javascript
4条回答
在下西门庆
2楼-- · 2020-02-29 20:06

You could also do that :

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

查看更多
何必那么认真
3楼-- · 2020-02-29 20:19

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
查看更多
Bombasti
4楼-- · 2020-02-29 20:25

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;
}
查看更多
ら.Afraid
5楼-- · 2020-02-29 20:28

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;
    };
查看更多
登录 后发表回答