doing substring in [removed].hash

后端 未结 4 1698
渐次进展
渐次进展 2021-01-03 12:29

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         


        
相关标签:
4条回答
  • 2021-01-03 13:06

    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;
    }
    
    0 讨论(0)
  • 2021-01-03 13:15

    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
    
    0 讨论(0)
  • 2021-01-03 13:19

    You could also do that :

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

    0 讨论(0)
  • 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;
        };
    
    0 讨论(0)
提交回复
热议问题